<?php

namespace app\erp\controller;

use app\erp\model\Buildtpldb;
use app\erp\model\Invoicedb;
use app\erp\model\JOrderdb;
use app\erp\model\Orderdb;
use app\erp\model\Expressdb;
use app\erp\model\Cartdb;
use app\erp\model\Installdb;
use app\erp\model\OrderGoodsRemarkdb;
use app\erp\model\OrderImagedb;
use app\erp\model\OrderOutGoodsdb;
use app\erp\model\OrderRemarkdb;
use app\erp\model\Pikuanxinxidb;
use app\erp\model\Postwuliudb;
use app\erp\model\Returneddb;
use app\erp\model\Runsdb;
use app\erp\model\Sitedb;
use app\api\controller\Neimeng;
use app\api\controller\Henan;
use app\api\controller\Qixin;
use app\erp\model\Memberdb;
use app\erp\model\OrderLogdb;
use app\erp\model\UCartdb;
use app\erp\model\UOrderdb;
use app\erp\model\UOrderGoodsRemarkdb;
use app\erp\model\UOrderLogdb;
use app\erp\model\Uploaddb;
use app\erp\model\Yujingdb;
use app\supplier\controller\Hetong;
use think\Db;
use think\Cache;
use app\erp\model\Offerdb;
use app\erp\model\Shoppingdb;
use app\erp\model\Goodsdb;

class Order extends Base
{
    protected $base_url = 'http://tailongji.dixintong.com/';
    protected $db;
    protected $cols = array(
        array(
            'field' => 'order_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 190,
            'title' => '军网订单号',
            'templet' => '#out_order_noTpl'
        ),
        array(
            'field' => 'order_money',
            'width' => 100,
            'title' => '订单金额',
            'totalRow' => true
        ),
        array(
            'field' => 'supplier_rate_money',
            'width' => 100,
            'title' => '采购金额',
            'totalRow' => true
        ),
        array(
            'field' => 'order_type',
            'width' => 90,
            'title' => '订单类型',
            'templet' => '#order_typeTpl'
        ),
        array(
            'field' => 'yewuyuan',
            'width' => 120,
            'title' => '业务员'
        ),
        array(
            'field' => 'neiqin',
            'width' => 80,
            'title' => '内勤'
        ),
        array(
            'field' => 'zhuli',
            'width' => 80,
            'title' => '助理'
        ),
        array(
            'field' => 'citys',
            'width' => 200,
            'title' => '省市'
        ),
        array(
            'field' => 'supplier_name',
            'width' => 240,
            'title' => '供应商',
            'templet' => '#supplier_nameTpl'
        ),
        array(
            'field' => 'last_supplier',
            'width' => 240,
            'title' => '上次指派'
        ),
        array(
            'field' => 'order_no',
            'width' => 160,
            'title' => '订单号'
        ),
        array(
            'field' => 'gys_fh_time',
            'width' => 150,
            'title' => '发货时间'
        ),
        array(
            'field' => 'apply_time',
            'width' => 150,
            'title' => '申请发票时间'
        ),
        array(
            'field' => 'remark',
            'width' => 120,
            'title' => '客服提醒'
        ),
        array(
            'field' => 'supplier_state',
            'width' => 60,
            'title' => '受理',
            'templet' => '#supplier_stateTpl'
        ),

        array(
            'field' => 'gys_fh_state',
            'width' => 90,
            'title' => '是否发货',
            'templet' => '#gys_fh_stateTpl'
        ),
        array(
            'field' => 'dingyue',
            'width' => 80,
            'title' => '订阅',
            'templet' => '#dingyueTpl'
        ),
        array(
            'field' => 'gys_sh_state',
            'width' => 90,
            'title' => '是否收货',
            'templet' => '#gys_sh_stateTpl'
        ),
        array(
            'field' => 'ruku',
            'width' => 60,
            'title' => '入库',
            'templet' => '#rukuTpl'
        ),
        array(
            'field' => 'apply_state',
            'width' => 90,
            'title' => '发票申请',
            'templet' => '#apply_stateTpl'
        ),
        array(
            'field' => 'returncode',
            'width' => 90,
            'title' => '电子发票',
            'templet' => '#returncodeTpl'
        ),
        array(
            'field' => 'invoice_proof',
            'width' => 90,
            'title' => '用户发票',
            'templet' => '#invoice_stateTpl'
        ),

        array(
            'field' => 'pay_state',
            'width' => 60,
            'title' => '收款',
            'templet' => '#pay_stateTpl'
        ),
        array(
            'field' => 'shopping_state',
            'width' => 60,
            'title' => '发货',
            'templet' => '#shopping_stateTpl'
        ),
        array(
            'field' => 'receipt_state',
            'width' => 60,
            'title' => '收货',
            'templet' => '#receipt_stateTpl'
        ),
        array(
            'field' => 'caigou_hetong',
            'width' => 90,
            'title' => '采购合同',
            'templet' => '#caigou_hetongTpl'
        ),
        array(
            'field' => 'caigou_invoice_duty',
            'width' => 90,
            'title' => '采购发票',
            'templet' => '#caigou_invoice_dutyTpl'
        ),
        array(
            'field' => 'ghs_pay',
            'width' => 60,
            'title' => '付款',
            'templet' => '#ghs_payTpl'
        ),
        array(
            'field' => 'gys_sh_time',
            'width' => 150,
            'title' => '收货时间'
        ),
        array(
            'field' => 'delivery_date',
            'width' => 120,
            'title' => '预计送达'
        ),
        array(
            'field' => 'shoukuan_time',
            'width' => 90,
            'title' => '收款计时'
        ),
        array(
            'field' => 'jun_order_state',
            'width' => 90,
            'title' => '推送状态',
            'templet' => '#jun_order_stateTpl'
        ),
        array(
            'field' => 'supplier_confirm_time',
            'width' => 120,
            'title' => '确认订单时间'
        ),
        array(
            'field' => 'supplier_rate',
            'width' => 90,
            'title' => '折扣率%'
        ),

        array(
            'field' => 'shopping_time',
            'width' => 120,
            'title' => '配送时间'
        ),
        array(
            'field' => 'contacts',
            'width' => 120,
            'title' => '收货人'
        ),
        array(
            'field' => 'contacts_phone',
            'width' => 120,
            'title' => '收货人电话'
        ),

        array(
            'field' => 'receipt_time',
            'width' => 120,
            'title' => '收货日期'
        ),
        array(
            'fixed' => 'right',
            'width' => 120,
            'toolbar' => '#order_tool',
            'title' => '日志'
        )
    );
    protected $member_cols = array(
        array(
            'field' => 'member_id',
            'width' => 40,
            'title' => '编号',
            'type' => 'radio'
        ),
        array(
            'field' => 'username',
            'width' => 160,
            'title' => '登录名',
            'sort' => 'true'
        ),
        array(
            'field' => 'realname',
            'width' => 160,
            'title' => '姓名',
            'sort' => 'true'
        ),
        array(
            'field' => 'phone',
            'width' => 160,
            'title' => '联系电话',
            'sort' => 'true'
        ),
        array(
            'field' => 'email',
            'width' => 220,
            'title' => '邮箱',
            'sort' => 'true'
        )
    );
    protected $goods_cols = array(
        array(
            'field' => 'category_name',
            'title' => '分类'
        ),
        array(
            'field' => 'brand_name',
            'title' => '品牌'
        ),
        array(
            'field' => 'goods_sku',
            'title' => '商品编号'
        ),
        array(
            'field' => 'goods_name',
            'title' => '商品名称'
        ),
        array(
            'field' => 'sale_price',
            'width' => 100,
            'title' => '价格',
            'edit' => true,
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'num',
            'title' => '数量',
            'width' => 80,
            'edit' => true,
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'width' => 100,
            'toolbar' => '#goods_tool',
            'title' => '操作',
            'fixed' => 'right'
        )
    );
    protected $goods_cols_state2 = array(
        array(
            'width' => 40,
            'field' => 'goods_id',
            'title' => '编号',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'width' => 120,
            'toolbar' => '#goods_tool',
            'title' => '操作',
            'fixed' => 'left'

        ),
        array(
            'field' => 'chengbenjia',
            'width' => 100,
            'title' => '运营备注一',
            'hide' => true
        ),
        array(
            'field' => 'category_name',
            'width' => 90,
            'title' => '分类'
        ),
        array(
            'width' => 120,
            'field' => 'jun_id',
            'title' => '军网编码'
        ),
        array(
            'width' => 190,
            'field' => 'goods_name',
            'title' => '商品名称'
        ),
        array(
            'field' => 'sale_price',
            'width' => 110,
            'title' => '价格',
            'style' => 'font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'num',
            'title' => '数量',
            'width' => 60,
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'buhanshui',
            'width' => 110,
            'title' => '不含税金额',
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'shuie',
            'width' => 110,
            'title' => '税额',
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'width' => 120,
            'field' => 'shuiwu_id',
            'title' => '税务编码'
        ),
        array(
            'width' => 230,
            'field' => 'product_area',
            'title' => '税务大类'
        ),
        array(
            'width' => 130,
            'field' => 'product_firm',
            'title' => '开票名称'
        ),
        array(
            'width' => 260,
            'field' => 'invoice_model',
            'title' => '规格型号'
        ),
        array(
            'width' => 60,
            'field' => 'goods_keywords',
            'title' => '税率'
        ),
        array(
            'field' => 'cart_goods_beizhu',
            'width' => 110,
            'title' => '备注',
            'edit' => true
        ),
        array(
            'field' => 'goods_sku',
            'width' => 90,
            'title' => '商品编号'
        ),
        array(
            'field' => 'manage_department',
            'width' => 100,
            'title' => '管理部门'
        ),
        array(
            'width' => 90,
            'field' => 'zhenshi',
            'title' => '真实库存',
            'hide' => true
        ),
        array(
            'width' => 90,
            'field' => 'caigoujia',
            'title' => '成本价'
        ),
        array(
            'field' => 'beizhu',
            'width' => 100,
            'title' => '运营备注二'
        ),

        array(
            'field' => 'gongyingshang',
            'width' => 160,
            'title' => '报备供应商'
        ),
        array(
            'field' => 'shenqingtime',
            'width' => 150,
            'title' => '申请时间'
        ),
        array(
            'field' => 'yewuyuan',
            'width' => 100,
            'title' => '业务员'
        )
    );
    protected $order_out_goods = array(
        array(
            'width' => 40,
            'field' => 'id',
            'title' => '编号',
            'type' => 'checkbox'
        ),
        array(
            'width' => 120,
            'toolbar' => '#out_goods_tool',
            'title' => '操作',

        ),
        array(
            'field' => 'yunyingbeizhu',
            'width' => 100,
            'title' => '运营备注一'
        ),
        array(
            'field' => 'baobeigongyingshang',
            'width' => 160,
            'title' => '报备供应商'
        ),
        array(
            'field' => 'shengqingshijian',
            'width' => 150,
            'title' => '申请时间'
        ),
        array(
            'field' => 'yewuyuan',
            'width' => 100,
            'title' => '业务员'
        ),
        array(
            'field' => 'fenlei',
            'width' => 90,
            'title' => '分类'
        ),
        array(
            'width' => 120,
            'field' => 'junwangbianhao',
            'title' => '军网编码'
        ),
        array(
            'width' => 190,
            'field' => 'shagpinmingcheng',
            'title' => '商品名称'
        ),
        array(
            'field' => 'jiage',
            'width' => 110,
            'title' => '价格',
            'style' => 'font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'shuliang',
            'title' => '数量',
            'width' => 60,
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'buhanshuijine',
            'width' => 110,
            'title' => '不含税金额',
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'field' => 'shuie',
            'width' => 110,
            'title' => '税额',
            'style' => 'text-align:center;font-size:16px;color:#ff6600'
        ),
        array(
            'width' => 120,
            'field' => 'shuiwubianma',
            'title' => '税务编码'
        ),
        array(
            'width' => 230,
            'field' => 'shuiwudalei',
            'title' => '税务大类'
        ),
        array(
            'width' => 130,
            'field' => 'kaipiaomingcheng',
            'title' => '开票名称'
        ),
        array(
            'width' => 260,
            'field' => 'guigexinghao',
            'title' => '规格型号'
        ),
        array(
            'width' => 60,
            'field' => 'shuilv',
            'title' => '税率'
        ),
        array(
            'width' => 90,
            'field' => 'zhenshikucun',
            'title' => '真实库存'
        ),
        array(
            'field' => 'beizhu',
            'width' => 110,
            'title' => '备注'
        ),
        array(
            'field' => 'shangpbianma',
            'width' => 90,
            'title' => '商品编号'
        )
    );

    protected $select_goods_cols = array(
        array(
            'field' => 'goods_id',
            'width' => 40,
            'type' => 'radio',
            'title' => '选择'
        ),
        array(
            'field' => 'category_name',
            'width' => 100,
            'title' => '分类'
        ),
        array(
            'field' => 'brand_name',
            'width' => 100,
            'title' => '品牌'
        ),
        array(
            'field' => 'goods_sku',
            'width' => 120,
            'title' => '商品编号'
        ),
        array(
            'field' => 'goods_name',
            'width' => 300,
            'title' => '商品名称'
        ),
        array(
            'field' => 'sale_price',
            'width' => 100,
            'title' => '售价'
        ),
        array(
            'field' => 'market_price',
            'width' => 100,
            'title' => '市场价'
        )
    );
    protected $cols_ghgys = array(
        array(
            'field' => 'order_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 190,
            'title' => '军网订单号'
        ),
        array(
            'field' => 'order_no',
            'width' => 160,
            'title' => '订单号'
        ),
        array(
            'field' => 'order_type',
            'width' => 90,
            'title' => '订单类型',
            'templet' => '#order_typeTpl'
        ),
        array(
            'field' => 'order_money',
            'width' => 100,
            'title' => '订单金额'
        ),
        array(
            'field' => 'create_time',
            'width' => 150,
            'title' => '下单时间'
        ),
        array(
            'field' => 'supplier_name',
            'width' => 120,
            'title' => '供货商'
        ),
        array(
            'field' => 'zhipai_date',
            'width' => 120,
            'title' => '指派时间'
        ),
        array(
            'fixed' => 'right',
            'width' => 80,
            'toolbar' => '#order_tool',
            'title' => '日志'
        )
    );
    protected $cols_feizhi = array(
        array(
            'field' => 'order_id',
            'width' => 40,
            'title' => 'ID',
            'type' => 'checkbox',
            'fixed' => 'left'
        ),
        array(
            'field' => 'supplier_name',
            'width' => 160,
            'title' => '供应商'
        ),
        array(
            'field' => 'out_order_no',
            'width' => 190,
            'title' => '军网订单号'
        ),
        array(
            'field' => 'order_no',
            'width' => 160,
            'title' => '订单号'
        ),
        array(
            'field' => 'order_type',
            'width' => 90,
            'title' => '订单类型',
            'templet' => '#order_typeTpl'
        ),
        array(
            'field' => 'order_money',
            'width' => 100,
            'title' => '订单金额'
        ),
        array(
            'field' => 'create_time',
            'width' => 150,
            'title' => '下单时间'
        ),
        array(
            'field' => 'cancel_time',
            'width' => 120,
            'title' => '废止时间'
        ),
        array(
            'fixed' => 'right',
            'width' => 80,
            'toolbar' => '#order_tool',
            'title' => '日志'
        )
    );
    protected $goods_cols_invoice = array(
        array(
            'field' => 'goods_sku',
            'title' => '商品编号',
            'hide' => true
        ),
        array(
            'width' => 250,
            'field' => 'product_area',
            'title' => '税务大类',
            'edit' => true
        ),
        array(
            'width' => 180,
            'field' => 'shuiwu_id',
            'title' => '税务编码',
            'edit' => true
        ),
        array(
            'width' => 130,
            'field' => 'product_firm',
            'title' => '开票名称',
            'edit' => true
        ),
        array(
            'width' => 300,
            'field' => 'invoice_model',
            'title' => '规格型号(若不要型号，只需输一个空格)',
            'edit' => true
        ),
        array(
            'width' => 60,
            'field' => 'goods_unit',
            'title' => '单位',
            'edit' => true
        ),
        array(
            'width' => 90,
            'field' => 'sale_price',
            'title' => '单价'
        ),

        array(
            'width' => 60,
            'field' => 'goods_num',
            'title' => '数量'
        ),
        array(
            'width' => 90,
            'field' => 'goods_keywords',
            'title' => '税率',
            'edit' => true
        ),
        array(
            'width' => 120,
            'field' => 'all_sale_price',
            'title' => '总金额'
        ),

        array(
            'width' => 120,
            'field' => 'diy_beizhu',
            'title' => '订单备注',
            'edit' => true
        )
    );
    protected $goods_cols_invoice_old = array(
        array(
            'field' => 'goods_sku',
            'title' => '商品编号',
            'hide' => true
        ),
        array(
            'width' => 120,
            'field' => 'product_area',
            'title' => '税务大类'
        ),
        array(
            'width' => 180,
            'field' => 'shuiwu_id',
            'title' => '税务编码'
        ),
        array(
            'width' => 130,
            'field' => 'product_firm',
            'title' => '开票名称'
        ),
        array(
            'width' => 300,
            'field' => 'invoice_model',
            'title' => '规格型号(若不要型号，只需输一个空格)'
        ),
        array(
            'width' => 60,
            'field' => 'goods_unit',
            'title' => '单位'
        ),
        array(
            'width' => 90,
            'field' => 'sale_price',
            'title' => '单价'
        ),
        array(
            'width' => 60,
            'field' => 'zhenshi',
            'title' => '真实库存'
        ),
        array(
            'width' => 60,
            'field' => 'goods_keywords',
            'title' => '税率'
        ),
        array(
            'width' => 120,
            'field' => 'all_sale_price',
            'title' => '总金额'
        )
    );
    public $post = array();

    public function _initialize()
    {
        ini_set('memory_limit', '256M');
        parent::_initialize();
        $request = request();
        $param = $request->param();
        $this->post = $param;
        $this->db = new Orderdb ();
        $this->db->param = $this->post;
    }

    /**
     * 导入订单入库
     */
    public function imploderuku()
    {
        set_time_limit(0);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $get_col_num = $sheet->getHighestColumn(); // 总列
                $phpexcel_shared_date = new \PHPExcel_Shared_Date ();
                $data = array();
                $text = '';
                $the_sheet = $objPHPExcel->getActiveSheet();
                $orderdb = new Orderdb();
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $temp ['out_order_no'] = $this->getSheetValue($the_sheet, "A" . $i);
                    $get_order = $orderdb->where('out_order_no', $temp['out_order_no'])->find();
                    if ($get_order) {
                        $save_order = [];
                        if (trim($this->getSheetValue($the_sheet, "B" . $i)))
                            $save_order['ruku'] = trim($this->getSheetValue($the_sheet, "B" . $i));
                        if (trim($this->getSheetValue($the_sheet, "C" . $i)))
                            $save_order['ruku_time'] = strtotime(trim($this->getSheetValue($the_sheet, "C" . $i)));
                        if (count($save_order) > 0) {
                            $get_order->save($save_order);
                            $uorderdb = new UOrderdb();
                            $get_uorder = $uorderdb->where('out_order_no', $temp['out_order_no'])->find();
                            if ($get_uorder) {
                                $get_uorder->save($save_order);
                            }
                            $order_logdb = new OrderLogdb ();
                            $order_logdb->param = array(
                                'type_index' => 0,
                                'order_no' => $get_order['order_no'],
                                'member_id' => MEMBER_ID,
                                'view_text' => '入库',
                                'post_json' => []
                            );
                            $order_logdb->saveData();
                            $uorder_logdb = new UOrderLogdb();
                            $save_data = array(
                                'type_index' => 0,
                                'order_no' => $get_order['order_no'],
                                'member_id' => MEMBER_ID,
                                'view_text' => '入库',
                                'post_json' => []
                            );
                            $uorder_logdb->save($save_data);
                        }
                    }
                }
                $this->layuiReturn($data, 0, '导入成功', 1);
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }

    // 同步发票文件
    public function snyInvoice()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        $order_arr = [];
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $the_sheet = $objPHPExcel->getActiveSheet();
                $orderdb = new Orderdb();
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $duty = (string)$this->getSheetValue($the_sheet, "B" . $i);
                    $order_no = $this->getSheetValue($the_sheet, "C" . $i);
                    // 验证是否已上传发票文件
                    $upload_id = [];
                    $duty_arr = [];
                    for ($j = 0; $j < 10; $j++) {
                        $uploaddb = new Uploaddb();
                        $get_upload = $uploaddb->where('file_name', $duty . '-' . $j . '.jpg')->find();
                        if ($get_upload) {
                            array_push($upload_id, $get_upload['upload_id']);
                            array_push($duty_arr, $duty);
                        } else {
                            if (is_file(ROOT_PATH . 'uploads/Excel/jinxiangpiao/' . $duty . '-' . $j . '.jpg')) {
                                $uploaddb = new Uploaddb();
                                $save_upload = [];
                                $save_upload['file_name'] = $duty . '-' . $j . '.jpg';
                                $save_upload['save_path'] = 'Excel/jinxiangpiao/' . $save_upload['file_name'];
                                $save_upload['type'] = 'image/jpeg';
                                $save_upload['size'] = 200;
                                $uploaddb->save($save_upload);
                                array_push($upload_id, $uploaddb->upload_id);
                                array_push($duty_arr, $duty);
                            }
                        }
                    }
                    // 验证订单是否存在
                    $get_order = $orderdb->where('out_order_no', $order_no)->find();
                    if ($get_order) {
                        // 验证订单试试已保存发票号
                        if (in_array($order_no, $order_arr)) {
                            // 不存在 保存
                            $caigou_duty = explode(',', $get_order['caigou_invoice_duty']);
                            $caigou_pz = explode(',', $get_order['caigou_invoice_pz']);
                            for ($x = 0; $x < count($duty_arr); $x++) {
                                array_push($caigou_duty, $duty_arr[$x]);
                                array_push($caigou_pz, $upload_id[$x]);
                            }
                        } else {
                            $caigou_pz = $upload_id;
                            $caigou_duty = $duty_arr;
                        }
                        $caigou_duty = array_filter($caigou_duty);
                        $caigou_pz = array_filter($caigou_pz);

                        $get_order->save([
                            'caigou_invoice_duty' => implode(',', $caigou_duty),
                            'caigou_invoice_pz' => implode(',', $caigou_pz),
                            'caigou_state' => 1,
                            'caigou_invoice_time' => time()
                        ]);
                        $yujingdb = new Yujingdb();
                        $get_yujing = $yujingdb->where('out_order_no', $order_no)->find();
                        if ($get_yujing) {
                            $get_yujing->save([
                                'caigou_invoice_time' => time(),
                                'step' => 5
                            ]);
                        }
                        array_push($order_arr, $order_no);
                    }
                }
                $this->layuiReturn('同步完成', 0, '同步完成', 1);
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }

    public function getShoppingPhone()
    {
        $this->layuiReturn('success');
    }

    // 废止订单
    public function feizhi()
    {
        $this->assign('feizhi_col', json_encode($this->cols_feizhi));
        return $this->fetch();
    }

    // 军采申请收款
    public function junShoukuan($order_no)
    {
        $junapi = new \app\jun\controller\Api();
        $get_order = $this->db->where('order_no', $order_no)->find();
        $post_json['tradeNo'] = $get_order['out_order_no'];
        $result = $junapi->ajaxConfirmReceipt($post_json);
        if ($result['isSuccess']) {
            $this->db->where('order_id', $get_order['order_id'])->update(['pay_state' => 2]);
            $this->layuiReturn('成功', 0, 'success', 1);
        } else {
            $this->layuiReturn($result['returnMsg'], 0, $result['returnMsg'], 0);
        }
    }

    // 更换供货商
    public function ghghs()
    {
        $this->assign('ghghs_col', json_encode($this->cols_ghgys));
        return $this->fetch();
    }

    public function getNeimengOrder()
    {
        $neimengapi = new Neimeng ();
        $return = $neimengapi->getOrderList();
    }

    public function getQixinOrder()
    {
        $qixinapi = new Qixin ();
        $return = $qixinapi->getOrderList();
    }

    public function pushHenan($order_no, $model = '')
    {
        $this->db->param ['order_no'];
        $get_order = $this->db->ajaxFind();
        $henanApi = new Henan ();
        if (isset ($model) && $model != '') {
            if ($model == 'contractDetail') {
                // 合同
                $henanApi->getContract($get_order ['out_order_no']);
            }
            if ($model == 'getOrderCheck') {
                // 验收状态
                $henanApi->getOrderCheck($get_order ['out_order_no']);
            }
            if ($model == 'payInfo') {
                // 确认支付
                $henanApi->orderPay($get_order);
            }
            if ($model == 'viewOrder') {
                // 查看订单
                $henanApi->getOrderInfo($get_order ['out_order_no']);
            }
            if ($model == 'sendInvoice') {
                // 开票
                $henanApi->sendInvoice($get_order ['out_order_no']);
            }
            if ($model == 'sendExpress') {
                // 发送唯一标识
                $post_data ['logisticsList'] = array(); // 发货时信息
                $expressdb = new Expressdb ();
                $expressdb->param ['order_no'] = $order_no;
                $get_express = $expressdb->ajaxList();
                $henanApi->sendOrderPic($get_order, $get_express);
            }
            if ($model == 'getInvoice') {
                $henanApi->signInvoice($get_order ['out_order_no']);
            }
            exit ();
        }
        if ($get_order ['order_state'] == 2) {
            // 确认订单
            $henanApi->confirmOrder($get_order ['out_order_no']);
        }
        if ($get_order ['order_state'] == 3) {
            $post_data ['logisticsList'] = array(); // 发货时信息
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $order_no;
            $get_express = $expressdb->ajaxList();
            // 发货
            $henanApi->express($get_express, $get_order ['out_order_no']);
        }
        if ($get_order ['order_state'] == 4) {
            // 订单收货
            $post_data ['logisticsList'] = array(); // 发货时信息
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $order_no;
            $get_express = $expressdb->ajaxList();
            $henanApi->signOrder($get_express, $get_order ['out_order_no']);
            //
        }
        if ($get_order ['order_state'] == -1) {
            // 取消订单
            $henanApi->channelOrder($get_order ['out_order_no']);
        }
        exit ();
    }

    public function pushNeimeng($order_no, $model = '')
    {
        $this->db->param ['order_no'];
        $get_order = $this->db->ajaxFind();
        $neimengapi = new Neimeng ();
        if (isset ($model) && $model != '') {
            if ($model == 'createContract') {
                $return = $neimengapi->createContract($get_order ['out_order_no']);
                if ($return ['code'] == 200) {
                    $this->db->param ['order_id'] = $get_order ['order_id'];
                    $this->db->param ['data'] = array(
                        'contract_no' => $return ['data']
                    );
                    $this->db->ajaxSaveOne();
                }
                echo '创建合同：' . $return ['message'];
            }
            if ($model == 'contractDetail') {
                $neimengapi->contractDetail($get_order ['contract_no']);
                // echo '获取合同：'.$return['message'];
            }
            if ($model == 'sendContract') {
                $neimengapi->sendContract($get_order ['contract_no']);
                // echo '发送合同：'.$return['message'];
            }
            exit ();
        }
        if ($get_order ['order_state'] == -1) {
            $return = $neimengapi->channelOrder($get_order ['out_order_no']);
            echo '订单取消状态：' . $return ['message'];
        } elseif ($get_order ['order_state'] == 4) {
            // 创建结算单
            $return = $neimengapi->createSettlement($get_order);
            echo '创建结算单：' . $return ['message'];
        } else {
            $return = $neimengapi->setOrder($order_no);
            echo '订单状态信息推送:' . $return ['message'];
            if ($return ['code'] != 200) {
                $this->db->param ['order_no'] = $order_no;
                $this->db->param ['data'] ['order_state'] = 2;
                // $this->db->saveStateBack();
            }
        }
    }

    public function pushQixin($order_no, $model = '')
    {
        $this->db->param ['order_no'];
        $get_order = $this->db->ajaxFind();
        $qixinapi = new Qixin ();
        if (isset ($model) && $model != '') {
            if ($model == 'createContract') {
                $return = $qixinapi->createContract($get_order ['out_order_no']);
                if ($return ['code'] == 200) {
                    $this->db->param ['order_id'] = $get_order ['order_id'];
                    $this->db->param ['data'] = array(
                        'contract_no' => $return ['data']
                    );
                    $this->db->ajaxSaveOne();
                }
                echo '创建合同：' . $return ['message'];
            }
            if ($model == 'contractDetail') {
                $qixinapi->contractDetail($get_order ['contract_no']);
                // echo '获取合同：'.$return['message'];
            }
            if ($model == 'sendContract') {
                $qixinapi->sendContract($get_order ['contract_no']);
                // echo '发送合同：'.$return['message'];
            }
            exit ();
        }
        if ($get_order ['order_state'] == -1) {
            $return = $qixinapi->channelOrder($get_order ['out_order_no']);
            echo '订单取消状态：' . $return ['message'];
        } elseif ($get_order ['order_state'] == 4) {
            // 创建结算单
            $return = $qixinapi->createSettlement($get_order);
            echo '创建结算单：' . $return ['message'];
        } else {
            $return = $qixinapi->setOrder($order_no);
            echo '订单状态信息推送:' . $return ['message'];
            if ($return ['code'] != 200) {
                $this->db->param ['order_no'] = $order_no;
                $this->db->param ['data'] ['order_state'] = 2;
                // $this->db->saveStateBack();
            }
        }
    }

    public function index()
    {
        // 获取分站信息
        $sitedb = new Sitedb ();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        $this->assign('get_site', $get_site);
        $this->assign('cols', json_encode($this->cols));
        // 获取分站列表
        $sitedb->param ['_o'] = 'site_id';
        $sitedb->param ['_b'] = 'asc';
        $sitedb->param ['page'] = 1;
        $sitedb->param ['limit'] = 1000;
        $get_site_list = $sitedb->ajaxSelect();
        $this->assign('site_list', $get_site_list ['data']);
        return $this->fetch();
    }

    /**
     *
     * @todo 列表
     */
    public function ajaxList()
    {
        //$get_list = $this->db->paginate($this->post['limit']);
        //$return = $get_list->items();
        $this->db->param['no_need_caigou_invoice_pz'] = 'yes';
        $this->db->param['no_need_ucaigou_invoice_pz'] = 'yes';
        $return = $this->db->ajaxSelect();
        foreach ($return['data'] as $key => $val) {
            // 处理上次指派的供应商
            $chk_s = $this->db
                ->useGlobalScope(false)
                ->where('phone', $val['phone'])
                ->where('supplier_id', '>', 0)
                ->where('order_id', '<', $val['order_id'])
                ->order('order_id desc')
                ->value('supplier_id');
            $last_supplier = '未指派过供应商';
            if ($chk_s) {
                $memberdb = new Memberdb ();
                $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $chk_s)->value('supplier_name');
                if ($get_supplier) {
                    $last_supplier = $get_supplier;
                }
            }
            $return['data'][$key]['last_supplier'] = $last_supplier;
        }
        $this->layuiReturn($return['data'], $return['count']);
        //$this->layuiReturn($return, $get_list->total());
    }

    public function ajaxListBack()
    {
        //$get_list = $this->db->paginate($this->post['limit']);
        //$return = $get_list->items();
        $return = $this->db->ajaxSelect();
        foreach ($return['data'] as $key => $val) {
            // 处理上次指派的供应商
            $temp_s = json_decode($val ['api_param'], true);
            $this->assign('jun_param', $temp_s);
            $chk_s = $this->db->useGlobalScope(false)->where('api_param', 'like', '%' . $temp_s ['mobile'] . '%')->where('supplier_id', '>', 0)->order('order_id desc')->value('supplier_id');
            $last_supplier = '未指派过供应商';
            if ($chk_s) {
                $memberdb = new Memberdb ();
                $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $chk_s)->value('supplier_name');
                if ($get_supplier) {
                    $last_supplier = $get_supplier;
                }
            }
            $return['data'][$key]['last_supplier'] = $last_supplier;
        }
        $this->layuiReturn($return['data'], $return['count']);
        //$this->layuiReturn($return, $get_list->total());
    }

    public function exportOrderBack()
    {
        set_time_limit(0);
        $count = $this->db->ajaxCount();
        $this->db->param ['page'] = 1;
        $this->db->param ['limit'] = $count;
        $this->db->param ['need_goods_info'] = 'yes';
        $data = $this->db->ajaxList();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '订单' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '订单号',
            '外部订单号',
            '订单时间',
            '订单金额',
            '收货地址',
            '收货人',
            '收货人电话',
            '订单状态',
            '支付状态',
            '发票状态',
            '配送状态',
            '配送时间',
            '收货状态',
            '收货日期',
            '订单备注',
            '订单产品',
            '产品编号',
            '购买数量',
            '销售金额',
            '小计'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_state_arr = array(
            '1' => '下单成功',
            '2' => '已确认订单',
            '3' => '订单已发货',
            '4' => '订单已收货',
            '5' => '订单已完成',
            '-1' => '订单已取消'
        );
        $pay_state_arr = array(
            '1' => '等待付款',
            '2' => '已付款',
            '3' => '部分付款'
        );
        $invoice_state_arr = array(
            '1' => '未开票',
            '2' => '已开票',
            '3' => '部分开票'
        );
        $shopping_state_arr = array(
            '1' => '未配送',
            '2' => '已配送',
            '3' => '部分配送'
        );
        $receipt_state_arr = array(
            '1' => '未收货',
            '2' => '已收货',
            '3' => '部分收货'
        );
        foreach ($data as $key => $val) {
            foreach ($val ['cart_info'] as $k => $v) {
                unset ($temp);
                $pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                $temp [0] = "\t" . $val ['order_no'];
                $temp [1] = "\t" . $val ['out_order_no'];
                $temp [2] = $val ['create_time'];
                $temp [3] = $val ['order_money'];
                $temp [4] = $val ['shopping_info'] ['province_name'] . $val ['shopping_info'] ['city_name'] . $val ['shopping_info'] ['area_name'] . $val ['shopping_info'] ['street'];
                $temp [5] = $val ['contacts'];
                $temp [6] = "\t" . $val ['contacts_phone'];
                $temp [7] = $order_state_arr [$val ['order_state']];
                $temp [8] = $pay_state_arr [$val ['pay_state']];
                $temp [9] = $invoice_state_arr [$val ['invoice_state']];
                $temp [10] = $shopping_state_arr [$val ['shopping_state']];
                $temp [11] = $val ['shopping_time'];
                $temp [12] = $receipt_state_arr [$val ['receipt_state']];
                $temp [13] = $val ['receipt_time'];
                $temp [14] = $val ['remark'];
                $temp [15] = $v ['goods_info'] ['goods_name'];
                $temp [16] = $v ['goods_sku'];
                $temp [17] = $v ['goods_num'];
                $temp [18] = $v ['goods_price'];
                $temp [19] = $v ['goods_num'] * $v ['goods_price'];
                array_push($excel_data, $temp);
            }
        }

        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    protected function createWhere($param)
    {
        unset($param['page']);
        $where = 'where `order`.order_money>0 AND `order`.delete_time IS NULL';
        $order_search = Db::name('member')->where('member_id', MEMBER_ID)->field('order_search,view_pre_order')->find();
        if ($order_search['order_search'] == 2) {
            $supplier_id_arr = Db::name('member')
                ->where('', 'exp', 'FIND_IN_SET(' . MEMBER_ID . ',be_staff_id)')
                ->column('member_id');
            if (count($supplier_id_arr)) {
                if ($order_search['view_pre_order'] == 1) {
                    $new_supplier_id_arr = $supplier_id_arr;
                    array_push($new_supplier_id_arr, 0);
                    $where .= ' and (`order`.supplier_id in (' . implode(',', $new_supplier_id_arr) . ') or `order`.supplier_er in (' . implode(',', $supplier_id_arr) . '))';
                } else {
                    $where .= ' and (`order`.supplier_id in (' . implode(',', $supplier_id_arr) . ') or `order`.supplier_er in (' . implode(',', $supplier_id_arr) . '))';
                }
            } else {
                if ($order_search['view_pre_order'] == 1) {
                    $where .= ' and `order`.supplier_id = 0';
                } else {
                    $where .= ' and `order`.order_id = 0';
                }
            }
        } else {
            if ($order_search['view_pre_order'] == 2) {
                $where .= ' and `order`.supplier_id > 0';
            }
        }

        foreach ($param as $key => $val) {
            if (!$val) {
                continue;
            }
            switch ($key) {

                case '_b':
                case '_o':
                case 'pname_id':
                case 'cname_id':
                case 'remark_type':
                case 'member_remark_type':
                case 'suppler_bz_type':
                    // 上面这些不参与查询
                    break;
                case 'cname':
                    // 城市
                    $where .= ' AND `shopping`.city = "' . $val . '"';
                    break;
                case 'pname':
                    // 省份
                    /*if(isset($param['cname'])){
                        $where_son = ' AND (`order`.api_param like "%' . $param['cname'] . '%" OR `order`.api_param like "%' . $param['cname_id'] . '%")';
                    } else {
                        $where_son = '';
                    }
                    $where .= ' AND ((`order`.api_param like "%' . $val . '%" OR `order`.api_param like "%' . $param['pname_id'] . '%") '.$where_son.')';*/
                    $where .= ' AND `shopping`.province = "' . $val . '"';
                    break;
                case 'shouhou_type':
                    // 售后类型
                    if ($val == 100) {
                        $where .= ' AND `order`.shouhou_type > 1';
                    } else {
                        $where .= ' AND `order`.shouhou_type = ' . $val;
                    }
                    break;
                case 'min_order_money':
                    // 订单金额
                    $where .= ' AND `order`.order_money >= ' . ($val * 100);
                    break;
                case 'max_order_money':
                    // 订单金额
                    $where .= ' AND `order`.order_money <= ' . ($val * 100);
                    break;
                case 'susername':
                    // 库房
                    $where .= ' AND member.supplier_name LIKE "%' . $val . '%" AND member.is_supplier = 1';
                    break;
                case 'yewuyuan':
                    // 业务员
                    $where .= ' AND member.yewuyuan LIKE "%' . $val . '%" AND member.is_supplier = 1';
                    break;
                case 'zhuli':
                    // 助理
                    $where .= ' AND member.zhuli LIKE "%' . $val . '%" AND member.is_supplier = 1';
                    break;
                case 'neiqin':
                    // 内勤
                    $where .= ' AND member.neiqin LIKE "%' . $val . '%" AND member.is_supplier = 1';
                    break;
                case 'j_address':
                    // 地址
                    $where .= ' AND shopping.street LIKE "%' . $val . '%" and shopping.member_id = 193';
                    break;
                case 'order_type_time_start':
                case 'create_time_start':
                case 'push_supplier_time_start':
                case 'supplier_confirm_time_start':
                case 'gys_fh_time_start':
                case 'gys_sh_time_start':
                case 'ruku_time_start':
                case 'apply_time_start':
                case 'apply_shehe_time_start':
                case 'invoice_time_start':
                case 'jc_fh_time_start':
                case 'jc_sh_time_start':
                case 'caigou_invoice_time_start':
                case 'ghs_pay_time_start':
                    // 时间查询 开始状态
                    $field = str_replace('_start', '', $key);
                    $where .= ' AND `order`.' . $field . ' >= ' . strtotime($val);
                    break;
                case 'order_type_time_end':
                case 'gys_fh_time_end':
                case 'gys_sh_time_end':
                case 'apply_time_end':
                case 'apply_shehe_time_end':
                case 'invoice_time_end':
                case 'jc_fh_time_end':
                case 'jc_sh_time_end':
                case 'caigou_invoice_time_end':
                    // 时间查询 结束状态
                    $field = str_replace('_end', '', $key);
                    $where .= ' AND `order`.' . $field . ' < ' . strtotime($val);
                    break;
                case 'create_time_end':
                case 'push_supplier_time_end':
                case 'supplier_confirm_time_end':
                case 'ruku_time_end':
                case 'ghs_pay_time_end':
                    // 时间查询 结束状态+1天
                    $field = str_replace('_end', '', $key);
                    $where .= ' AND `order`.' . $field . ' < ' . strtotime('+ 1 day', strtotime($val));
                    break;
                case 'apply_state':
                    // 申请票
                    if ($val == -1) {
                        $where .= ' AND `order`.apply_state > 1';
                    } else {
                        $where .= ' AND `order`.apply_state > ' . $val;
                    }
                    break;
                case 'returncode':
                    //电子票
                    if ($val == 1) {
                        $where .= ' AND `order`.returncode IS NULL';
                    } elseif ($val == 2) {
                        $where .= ' AND `order`.returncode = "成功"';
                    } elseif ($val == 3) {
                        $where .= ' AND `order`.returncode = "线下开具成功"';
                    } elseif ($val == 4) {
                        $where .= ' AND `order`.returncode = "红冲成功"';
                    } elseif ($val == 5) {
                        $where .= ' AND `order`.returncode like "%红冲成功%"';
                    }
                    break;
                case 'caigou_hetong':
                    // 采购合同
                    if ($val == 1) {
                        $where .= ' AND `order`.caigou_hetong IS NULL';
                    } elseif ($val == 2) {
                        $where .= ' AND `order`.caigou_hetong IS NOT NULL';
                    }
                    break;
                case 'caigou_invoice_duty':
                    // 采购发票
                    if ($val == 1) {
                        $where .= ' AND `order`.caigou_invoice_duty IS NULL';
                    } elseif ($val == 2) {
                        $where .= ' AND `order`.caigou_invoice_duty IS NOT NULL';
                    }
                    break;
                case 'remark':
                    //客服提醒
                    if (isset($param['remark_type']) && $param['remark_type'] == '2') {
                        $where .= ' AND `order`.remark IS NOT NULL AND `order`.remark NOT LIKE "%' . $val . '%"';
                    } else {
                        $where .= ' AND `order`.remark LIKE "%' . $val . '%"';
                    }
                    break;
                case 'member_remark':
                    // 备注
                    if (isset($param['member_remark_type']) && $param['member_remark_type'] == '2') {
                        $where .= ' AND `order`.member_remark IS NOT NULL AND `order`.member_remark NOT LIKE "%' . $val . '%"';
                    } else {
                        $where .= ' AND `order`.member_remark LIKE "%' . $val . '%"';
                    }
                    break;
                case 'suppler_bz':
                    // 供货商备注
                    if (isset($param['suppler_bz_type']) && $param['suppler_bz_type'] == '2') {
                        $where .= ' AND `order`.suppler_bz IS NOT NULL AND `order`.suppler_bz NOT LIKE "%' . $val . '%"';
                    } else {
                        $where .= ' AND `order`.suppler_bz LIKE "%' . $val . '%"';
                    }
                    break;
                case 'order_type':
                    if ($val == 11) {
                        $where .= ' AND `order`.order_type NOT IN (5,7)';
                    } else {
                        $where .= 'AND `order`.order_type = ' . $val;
                    }
                    break;
                default:
                    // 通用LIKE
                    if (in_array($key, ['order_no', 'out_order_no', 'phone'])) {
                        $where .= ' AND `order`.' . $key . ' LIKE "%' . $val . '%"';
                    } else {
                        // 通用 =
                        $where .= ' AND `order`.' . $key . ' = "' . $val . '"';
                    }

                    break;
            }
        }
        return $where;
    }

    public function exportOrderNew()
    {
        set_time_limit(0);
        ini_set('memory_limit', '12000M');
        $where = $this->createWhere($this->request->param());
        $sql = 'SELECT `order`.out_order_no,
	FROM_UNIXTIME(`order`.create_time) create_time,
	`order`.order_type,
	`order`.shouhou_type,
	`order`.order_money / 100 AS order_money,
	`order`.jun_order_state,
	shopping.province,
	shopping.city,
	shopping.area,
	shopping.street,
	shopping.contacts,
	shopping.phone,
	`order`.api_param,
	`order`.supplier_rate / 100 AS supplier_rate,
	`order`.huikuandanwei,
	member.supplier_name,
	FROM_UNIXTIME(`order`.push_supplier_time) push_supplier_time,
	FROM_UNIXTIME(`order`.supplier_confirm_time) supplier_confirm_time,
	`order`.gys_fh_state,
	FROM_UNIXTIME(`order`.gys_fh_time) gys_fh_time,
	`order`.shopping_state,
	FROM_UNIXTIME(`order`.jc_fh_time) jc_fh_time,
	`order`.gys_sh_state,
	FROM_UNIXTIME(`order`.gys_sh_time) gys_sh_time,
	`order`.receipt_state,
	FROM_UNIXTIME(`order`.jc_sh_time) jc_sh_time,
	`order`.caigou_invoice_duty,
	FROM_UNIXTIME(`order`.caigou_invoice_time) caigou_invoice_time,
	`order`.invoice_state,
	FROM_UNIXTIME(`order`.apply_time) apply_time,
	`order`.pay_state,
	FROM_UNIXTIME(`order`.pay_time) pay_time,
	`order`.ghs_pay,
	FROM_UNIXTIME(`order`.ghs_pay_time) ghs_pay_time,
	`order`.remark,
	`order`.suppler_bz,
	`order`.ruku,
	FROM_UNIXTIME(`order`.ruku_time) ruku_time,
	`order`.apply_state,
	goods.goods_name,
	goods.goods_sku,
	goods.goods_model,
	goods.jun_id,
	goods.goods_son_name,
	goods.upc,
	cart.goods_num,
	cart.goods_price,
	cart.goods_price * cart.goods_num AS xiaoji,
	cart.goods_price * (`order`.supplier_rate / 100) AS caigoujiao,
	round(
		cart.goods_price * (`order`.supplier_rate / 100),
		2
	) * cart.goods_num AS caigoujiaoji,
	goods.goods_beizhu1,
	goods.goods_beizhu2,
	goods.goods_beizhu5,
	goods.invoice_model,
	goods.goods_unit
FROM
ys_order AS `order`
LEFT JOIN ys_invoice AS invoice ON invoice.order_nos = `order`.order_no
LEFT JOIN ys_member AS member ON member.member_id = `order`.supplier_id
LEFT JOIN ys_shopping AS shopping ON shopping.shopping_id = `order`.shopping_id
LEFT JOIN ys_cart AS cart ON cart.order_no = `order`.order_no
LEFT JOIN ys_goods AS goods ON goods.goods_sku = cart.goods_sku
' . $where . ' ORDER BY `order`.out_order_no asc';


        $data = Db::query($sql);
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '订单' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '军采单号',
            '订单时间',
            '订单类型',
            '售后类型',
            '订单金额',
            '订单状态',
            '收货地址',
            '收货人',
            '收货人电话',
            '用户备注',
            '折扣率',
            '汇款单位',
            '指定供应商',
            '指定供应商时间',
            '供应商确认时间',
            '供应商发货',
            '供应商发货时间',
            '同步军采发货',
            '同步军采发货时间',
            '供应商收货',
            '供应商收货时间',
            '同步军采收货',
            '同步军采收货时间',
            '上传采购发票',
            '上传采购发票时间',
            '上传用户发票',
            '申请开票时间',
            '收款',
            '收款时间',
            '付款',
            '付款时间',
            '客服提醒',
            '供应商备注',
            '入库',
            //'上次指派',
            '发票申请',
            '订单产品',
            '产品编号',
            '型号',
            '军网编号',
            'D名称',
            'D编号',
            '购买数量',
            '销售金额',
            '小计',
            '采购价',
            '采购小计',
            '快普货品编码',
            //'税务编码',
            '快普品牌',
            '快普物料名称',
            '规格型号',
            '单位'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_state_arr = array(
            '1' => '下单成功',
            '2' => '已确认订单',
            '3' => '订单已发货',
            '4' => '订单已收货',
            '5' => '订单已完成',
            '-1' => '订单已取消',
            '-2' => '重新指派'
        );
        $jun_order_state_arr = array(
            '0' => '无效订单',
            '1' => '待确认',
            '2' => '待发货',
            '3' => '待支付',
            '4' => '待收货',
            '5' => '已完成',
            '6' => '已退货',
            '7' => '已取消',
            '8' => '待妥投',
            '9' => '已废止',
            '-2' => '未采集',
            '-1' => '未采集'
        );
        $pay_state_arr = array(
            '1' => '未收款',
            '2' => '已收款',
            '3' => '部分支付',
            '4' => '质保金支付 '
        );
        $pay_type_arr = array(
            '1' => '货到付款',
            '2' => '在线支付',
            '3' => '账期支付',
            '4' => '银行转账'
        );
        $is_invoice_arr = array(
            '1' => '不开票',
            '2' => '独立开票',
            '3' => '统一开票'
        );
        $invoice_state_arr = array(
            '1' => '未开票',
            '2' => '已开票',
            '3' => '部分开票'
        );
        $shopping_state_arr = array(
            '1' => '未配送',
            '2' => '已配送',
            '3' => '部分配送'
        );
        $receipt_state_arr = array(
            '1' => '未收货',
            '2' => '已收货',
            '3' => '部分收货'
        );
        $gys_fh_state_arr = array(
            '1' => '已发货',
            '2' => '未发货'
        );
        $gys_sh_state_arr = array(
            '1' => '已收货',
            '2' => '未收货'
        );
        $caigou_hetong_arr = array(
            '1' => '未上传',
            '2' => '已上传'
        );
        $caigou_invoice_duty_arr = array(
            '2' => '未开票',
            '1' => '已开票'
        );
        $ghs_pay_arr = array(
            '1' => '全部付款',
            '2' => '质保金付款',
            '3' => '部分付款',
            '4' => '未付款'
        );
        $apply_state_arr = array(
            '' => '未提交',
            '1' => '未提交',
            '2' => '等待审核',
            '3' => '审核通过',
            '4' => '驳回'
        );
        $ruku_arr = array(
            '1' => '已入库',
            '2' => '未入库'
        );
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        $shouhou_type_arr = array(
            '1' => '无售后',
            '2' => '漏发货',
            '3' => '多发货',
            '4' => '错发',
            '5' => '换货',
            '6' => '退货',
            '7' => '维修调试',
            '8' => '安装'
        );
        foreach ($data as $key => $val) {
            $temp [0] = $val ['out_order_no'] . " ";
            $temp [1] = $val ['create_time'];
            $temp [2] = $order_type_arr [$val ['order_type']];
            $temp [3] = $shouhou_type_arr [$val ['shouhou_type']];
            $temp [4] = number_format($val ['order_money'], 2, '.', '');
            $temp [5] = $jun_order_state_arr [$val ['jun_order_state']];
            $temp [6] = $val ['province'] . $val['city'] . $val['area'] . $val['street'];
            $temp [7] = $val ['contacts'];
            $temp [8] = $val ['phone'] . " ";
            $yonghu_beizhu = json_decode($val['api_param'], true);
            $temp [9] = $this->filterEmoji($yonghu_beizhu ['remark']);
            $temp [10] = ($val['supplier_rate'] * 100) . '%';
            $temp [11] = $val ['huikuandanwei'];
            $temp [12] = $val ['supplier_name'];
            $temp [13] = $val ['push_supplier_time'];
            $temp [14] = $val ['supplier_confirm_time'];
            $temp [15] = $gys_fh_state_arr [$val ['gys_fh_state']];
            $temp [16] = $val ['gys_fh_time'] ? $val ['gys_fh_time'] : '';
            $temp [17] = $shopping_state_arr [$val ['shopping_state']];
            $temp [18] = $val ['jc_fh_time'] ?? '';
            $temp [19] = $gys_sh_state_arr [$val ['gys_sh_state']];
            $temp [20] = $val ['gys_sh_time'] ?? '';
            $temp [21] = $receipt_state_arr [$val ['receipt_state']];
            $temp [22] = $val ['jc_sh_time'] ?? '';
            $temp [23] = $caigou_invoice_duty_arr [$val ['caigou_invoice_duty'] ? 1 : 2];
            $temp [24] = $val ['caigou_invoice_time'] ?? '';
            $temp [25] = $invoice_state_arr [$val ['invoice_state']];
            $temp [26] = $val ['apply_time'] ?? '';
            $temp [27] = $pay_state_arr [$val ['pay_state']];
            $temp [28] = $val ['pay_time'] ?? '';
            $temp [29] = $ghs_pay_arr [$val ['ghs_pay']];
            $temp [30] = $val ['ghs_pay_time'] ?? '';
            $temp [31] = $val ['remark'];
            //   $temp [32] = $val ['member_remark'];
            $temp [32] = $val ['suppler_bz'];
            $ruku_time = $val ['ruku_time'] ?? '';
            $temp [33] = $ruku_arr [$val ['ruku']] . ' | ' . $ruku_time;
            //$temp [34] = $val ['suppler_bz3'];
            // 上次指派
            //$temp [34] = '';
            $temp [34] = $apply_state_arr [$val ['apply_state']] ?? '';
            $temp [35] = str_replace('/', '/ ', $val ['goods_name']);
            $temp [36] = $val ['goods_sku'];
            $temp [37] = $val ['goods_model'] ?? '';
            $temp [38] = $val ['jun_id'];
            $temp [39] = str_replace('/', '/ ', $val ['goods_son_name']);
            $temp [40] = $val ['upc'] . " ";
            $temp [41] = $val ['goods_num'];
            $temp [42] = $val ['goods_price'];
            $temp [43] = $val['xiaoji'];
            $temp [44] = number_format($val['caigoujiao'], 2, '.', '');
            $temp [45] = number_format($val['caigoujiaoji'], 2, '.', '');
            $temp [46] = $val['goods_beizhu1'] . " ";
            //$temp [48] = $v['shuiwu_id'] ?: $v['goods_info']['shuiwu_id'] . ' ';
            $temp [47] = $val['goods_beizhu2'];
            $temp [48] = $val['goods_beizhu5'] . " ";
            $temp [49] = $val['invoice_model'];
            $temp [50] = $val['goods_unit'];
            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBodynew($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    /**
     * Title("导出本次查询订单")
     */
    public function exportOrder()
    {
        set_time_limit(0);
        ini_set('memory_limit', '12000M');
        $get_order = $this->db->order('create_time desc')->select();
        if (!$get_order->isEmpty()) {
            $cartdb = new Cartdb ();
            $memberdb = new Memberdb ();
            $goodsdb = new Goodsdb ();
            $shoppingdb = new Shoppingdb ();
            //$get_order = $get_order->toArray();
            $new_order = array();
            foreach ($get_order as $key => $val) {
                $temp_api = json_decode($val['api_param'], true);
                $get_order[$key]['beizhu'] = isset($temp_api['remark']) ? $temp_api['remark'] : '';
                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'] / 100;
                if ($val ['supplier_id']) {
                    $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $val ['supplier_id'])->find()->toArray();
                    $get_order [$key] ['supplier_name'] = $get_supplier ['supplier_name'];
                    $get_order [$key] ['yewuyuan'] = $get_supplier ['yewuyuan'];
                } else {
                    $get_order [$key] ['supplier_name'] = '未指定供应商';
                    $get_order [$key] ['yewuyuan'] = '';
                }
                $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $val ['order_no'])->select();
                if (!$get_cart->isEmpty()) {
                    $get_cart = $get_cart->toArray();
                    $zhekou_money = 0;
                    foreach ($get_cart as $k => $v) {
                        $zhekou_money += number_format(round($v ['goods_price'] * $val ['supplier_rate']) * $v ['goods_num'] / 100, 2, '.', '');
                        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $v ['goods_sku'])->where('site_id', SITE_ID)->find();
                        if ($get_goods) {
                            $get_cart [$k] ['goods_info'] = $get_goods->toArray();
                        }
                    }
                    $get_order [$key] ['supplier_rate_money'] = $zhekou_money;
                    $get_order [$key] ['cart_info'] = $get_cart;
                }
                $shop_info = array(
                    'contacts' => '无',
                    'phone' => '无'
                );
                if ($val ['shopping_id']) {
                    $get_shopping = $shoppingdb->useGlobalScope(false)->where('shopping_id', $val ['shopping_id'])->find();
                    if ($get_shopping) {
                        $shop_info = $get_shopping->toArray();
                    }
                }
                $get_order [$key] ['shopping_info'] = $shop_info;
                $temp = json_decode($val ['api_param'], true);
                $get_order [$key] ['citys'] = $temp ['Cityname'] . $temp ['address'];
                if ((isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') || (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes')) {
                    // 如果导出的是更换供货商 这里这不推送数据
                } else {
                    array_push($new_order, $get_order [$key]);
                }
                if (isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') {
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);
                        if ($temp_s > 1) {
                            for ($x = 0; $x < count($temp_s) - 1; $x++) {
                                $get_order [$key] ['order_state'] = -2;
                                $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                                $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                                $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                            }
                        }
                    }
                }
                if (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes') {
                    $supplier_name = '';
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);

                        if (count($temp_s) > 0) {
                            $supplier_name = $temp_s [count($temp_s) - 1] ['supplier_name'];
                        }
                    }
                    $get_order [$key] ['order_state'] = -2;
                    $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                    $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                    $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                    $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                }
            }
        }
        $data = $new_order;
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '订单' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '军采单号',
            '订单时间',
            '订单类型',
            '售后类型',
            '订单金额',
            '订单状态',
            '收货地址',
            '收货人',
            '收货人电话',
            '用户备注',
            '折扣率',
            '汇款单位',
            '来源',
            '指定供应商',
            '指定供应商时间',
            '供应商确认时间',
            '供应商发货',
            '供应商发货时间',
            '同步军采发货',
            '同步军采发货时间',
            '供应商收货',
            '供应商收货时间',
            '同步军采收货',
            '同步军采收货时间',
            '上传采购发票',
            '上传采购发票时间',
            '上传用户发票',
            '申请开票时间',
            '收款',
            '收款时间',
            '付款',
            '付款时间',
            '客服提醒',
            '供应商备注',
            '入库',
            '上次指派',
            '发票申请',
            '订单产品',
            '产品编号',
            '型号',
            '军网编号',
            'D名称',
            'D编号',
            '购买数量',
            '销售金额',
            '小计',
            '采购价',
            '采购小计',
            '快普货品编码',
            //'税务编码',
            '快普品牌',
            '快普物料名称',
            '规格型号',
            '单位',
            '运营备注1',
            '运营备注2',
            '备注',
            //'报备供应商'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_state_arr = array(
            '1' => '下单成功',
            '2' => '已确认订单',
            '3' => '订单已发货',
            '4' => '订单已收货',
            '5' => '订单已完成',
            '-1' => '订单已取消',
            '-2' => '重新指派'
        );
        $jun_order_state_arr = array(
            '0' => '无效订单',
            '1' => '待确认',
            '2' => '待发货',
            '3' => '待支付',
            '4' => '待收货',
            '5' => '已完成',
            '6' => '已退货',
            '7' => '已取消',
            '8' => '待妥投',
            '9' => '已废止',
            '-2' => '未采集',
            '-1' => '未采集'
        );
        $pay_state_arr = array(
            '1' => '未收款',
            '2' => '已收款',
            '3' => '部分支付',
            '4' => '质保金支付 '
        );
        $pay_type_arr = array(
            '1' => '货到付款',
            '2' => '在线支付',
            '3' => '账期支付',
            '4' => '银行转账'
        );
        $is_invoice_arr = array(
            '1' => '不开票',
            '2' => '独立开票',
            '3' => '统一开票'
        );
        $invoice_state_arr = array(
            '1' => '未开票',
            '2' => '已开票',
            '3' => '部分开票'
        );
        $shopping_state_arr = array(
            '1' => '未配送',
            '2' => '已配送',
            '3' => '部分配送'
        );
        $receipt_state_arr = array(
            '1' => '未收货',
            '2' => '已收货',
            '3' => '部分收货'
        );
        $gys_fh_state_arr = array(
            '1' => '已发货',
            '2' => '未发货'
        );
        $gys_sh_state_arr = array(
            '1' => '已收货',
            '2' => '未收货'
        );
        $caigou_hetong_arr = array(
            '1' => '未上传',
            '2' => '已上传'
        );
        $caigou_invoice_duty_arr = array(
            '2' => '未开票',
            '1' => '已开票'
        );
        $ghs_pay_arr = array(
            '1' => '全部付款',
            '2' => '质保金付款',
            '3' => '部分付款',
            '4' => '未付款'
        );
        $apply_state_arr = array(
            '' => '未提交',
            '1' => '未提交',
            '2' => '等待审核',
            '3' => '审核通过',
            '4' => '驳回'
        );
        $ruku_arr = array(
            '1' => '已入库',
            '2' => '未入库'
        );
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        $shouhou_type_arr = array(
            '1' => '无售后',
            '2' => '漏发货',
            '3' => '多发货',
            '4' => '错发',
            '5' => '换货',
            '6' => '退货',
            '7' => '维修调试',
            '8' => '安装'
        );
        foreach ($data as $key => $val) {
            $cg_money = 0;
            if (!isset($val ['cart_info'])) {
                continue;
            }
            // 处理上次指派的供应商
            $temp_s = json_decode($val ['api_param'], true);
            $this->assign('jun_param', $temp_s);
            $chk_s = $this->db->useGlobalScope(false)
                ->where('phone', $val ['phone'])
                ->where('supplier_id', '>', 0)
                ->where('order_id', '<', $val['order_id'])
                ->order('order_id desc')
                ->find();
            $last_supplier = '未指派过供应商';
            if ($chk_s) {
                $chk_s = $chk_s->toArray();
                $memberdb = new Memberdb ();
                $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $chk_s ['supplier_id'])->find();
                if ($get_supplier) {
                    $get_supplier = $get_supplier->toArray();
                    $last_supplier = $get_supplier ['supplier_name'];
                }
            }
            $return['data'][$key]['last_supplier'] = $last_supplier;
            foreach ($val ['cart_info'] as $k => $v) {
                if (isset($v ['goods_info']) && $v['goods_info']) {
                    unset ($temp);
                    $pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                    $supplier_rate = $val ['supplier_rate'] ? $val ['supplier_rate'] : 100;
                    $temp [0] = $val ['out_order_no'] . " ";
                    $temp [1] = $val ['create_time'];
                    $temp [2] = $order_type_arr [$val ['order_type']];
                    $temp [3] = $shouhou_type_arr [$val ['shouhou_type']];
                    $temp [4] = $val ['order_money'];
                    $temp [5] = $jun_order_state_arr [$val ['jun_order_state']];
                    $temp [6] = $val ['citys'];
                    $temp [7] = $val ['shopping_info'] ['contacts'];
                    $temp [8] = $val ['shopping_info'] ['phone'] . " ";
                    $temp [9] = $this->filterEmoji($val ['beizhu']);
                    $temp [10] = $supplier_rate . '%';
                    $temp [11] = $val ['huikuandanwei'];
                    $temp [12] = $val['hezuodanwei'];
                    $temp [13] = $val ['supplier_name'];
                    $temp [14] = $val ['push_supplier_time'];
                    $temp [15] = $val ['supplier_confirm_time'];
                    $temp [16] = $gys_fh_state_arr [$val ['gys_fh_state']];
                    $temp [17] = $val ['gys_fh_time'] ? $val ['gys_fh_time'] : '';
                    $temp [18] = $shopping_state_arr [$val ['shopping_state']];
                    $temp [19] = $val ['jc_fh_time'] ? date('Y-m-d H:i:s', $val ['jc_fh_time']) : '';
                    $temp [20] = $gys_sh_state_arr [$val ['gys_sh_state']];
                    $temp [21] = $val ['gys_sh_time'] ? $val ['gys_sh_time'] : '';
                    $temp [22] = $receipt_state_arr [$val ['receipt_state']];
                    $temp [23] = $val ['jc_sh_time'] ? date('Y-m-d H:i:s', $val ['jc_sh_time']) : '';
                    $temp [24] = $caigou_invoice_duty_arr [$val ['caigou_invoice_duty'] ? 1 : 2];
                    $temp [25] = $val ['caigou_invoice_time'] ? $val ['caigou_invoice_time'] : '';
                    $temp [26] = $invoice_state_arr [$val ['invoice_state']];
                    $temp [27] = $val ['apply_time'] ? $val ['apply_time'] : '';
                    $temp [28] = $pay_state_arr [$val ['pay_state']];
                    $temp [29] = $val ['pay_time'];
                    $temp [30] = $ghs_pay_arr [$val ['ghs_pay']];
                    $temp [31] = $val ['ghs_pay_time'] ? $val ['ghs_pay_time'] : '';
                    $temp [32] = $val ['remark'];
                    //   $temp [32] = $val ['member_remark'];
                    $temp [33] = $val ['suppler_bz'];
                    $ruku_time = $val ['ruku_time'] ? $val ['ruku_time'] : '';
                    $temp [34] = $ruku_arr [$val ['ruku']] . ' | ' . $ruku_time;
                    //$temp [34] = $val ['suppler_bz3'];
                    // 上次指派
                    $temp [35] = $last_supplier;
                    $temp [36] = $apply_state_arr [$val ['apply_state']] ?? '';
                    $temp [37] = str_replace('/', '/ ', $v ['goods_info'] ['goods_name']);
                    $temp [38] = $v ['goods_sku'];
                    $temp [39] = $v ['goods_info']['goods_model'] ?? '';
                    $temp [40] = $v ['goods_info'] ['jun_id'];
                    $temp [41] = str_replace('/', '/ ', $v ['goods_info'] ['goods_son_name']);
                    $temp [42] = $v ['goods_info'] ['upc'] . " ";
                    $temp [43] = $v ['goods_num'];
                    $temp [44] = $v ['goods_price'];
                    $temp [45] = number_format($v ['goods_price'] * $v ['goods_num'], 2, '.', '');
                    $zhekou = round($v ['goods_price'] * $supplier_rate) / 100;
                    $temp [46] = number_format($zhekou, 2, '.', '');
                    $temp [47] = number_format($temp [46] * $v ['goods_num'], 2, '.', '');
                    $cg_money += $temp [47];
                    $temp [48] = $v['goods_info']['goods_beizhu1'] . " ";
                    //$temp [48] = $v['shuiwu_id'] ?: $v['goods_info']['shuiwu_id'] . ' ';
                    $temp [49] = $v['goods_info']['goods_beizhu2'];
                    $temp [50] = $v['goods_info']['goods_beizhu5'] . " ";
                    $temp [51] = $v['invoice_model'] ?: $v['goods_info']['invoice_model'];
                    $temp [52] = $v['goods_unit'] ?: $v['goods_info']['goods_unit'];
                    $get_sale_price = Db::name('sale_price')->where('goods_sku', $v['goods_sku'])->field('chengbenjia,beizhu')->find();
                    $temp [53] = $get_sale_price['chengbenjia'];
                    $temp [54] = $get_sale_price['beizhu'];
                    $temp [55] = $v['goods_beizhu3'] ?: $v['goods_info']['goods_beizhu3'];
                    // 获取报备供应商
                    /*$get_baojia = Db::name('baojia')
                        ->where('goods_sku',$v['goods_sku'])
                        ->whereTime('create_time', '<', $v['create_time'])
                        ->order('baojia_id', 'desc')
                        ->field('baojia,apply_member_id')
                        ->find();
                    $temp [56] = '';
                    if($get_baojia['baojia'] == $v['goods_price']){
                        $temp [56] = Db::name('member')->where('member_id',$get_baojia['apply_member_id'])->value('supplier_name');
                    }*/
                    array_push($excel_data, $temp);
                }
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    /**
     * Title("导出财务订单")
     */
    public function exportCwOrder()
    {
        set_time_limit(0);
        ini_set('memory_limit', '12000M');
        $get_order = $this->db->order('create_time desc')->field('out_order_no,supplier_id,pay_state,pay_time,ghs_pay,ghs_pay_time,order_money,order_no,supplier_rate')->select();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '订单' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $header_data = array(
            '军采单号',
            '指定供应商',
            '收款',
            '收款时间',
            '付款',
            '付款时间',
            '订单金额',
            '采购金额'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $pay_state_arr = array(
            '1' => '未收款',
            '2' => '已收款',
            '3' => '部分支付',
            '4' => '质保金支付 '
        );
        $ghs_pay_arr = array(
            '1' => '全部付款',
            '2' => '质保金付款',
            '3' => '部分付款',
            '4' => '未付款'
        );
        $supplier_sql = $this->db->fetchSql(true)->group('supplier_id')->column('supplier_id');
        $get_supplier_arr = Db::name('member')->where('member_id', 'exp', 'in(' . $supplier_sql . ')')->column('supplier_name', 'member_id');
        $order_no_sql = $this->db->fetchSql(true)->column('order_no');
        $get_cart_arr = Db::name('cart')->where('order_no', 'exp', 'in(' . $order_no_sql . ')')->field('order_no,goods_sku,goods_num,goods_price')->select();
        foreach ($get_order as $key => $val) {
            $order_money = $get_order [$key] ['order_money'] / 100;
            if ($val ['supplier_id']) {
                $get_supplier = $get_supplier_arr[$val['supplier_id']];
            } else {
                $get_supplier = '未指定供应商';
            }
            $temp = [];
            $temp[0] = $val['out_order_no'];
            $temp[1] = $get_supplier;
            $temp[2] = $pay_state_arr [$val ['pay_state']];
            $temp[3] = $val ['pay_time'];
            $temp[4] = $ghs_pay_arr [$val ['ghs_pay']];
            $temp[5] = $val ['ghs_pay_time'] ? $val ['ghs_pay_time'] : '';
            $temp[6] = $order_money;
            $cg_money = 0;
            $supplier_rate = $val ['supplier_rate'] ?: 100;
            foreach ($get_cart_arr as $k => $v) {
                if ($v['order_no'] == $val['order_no']) {
                    $zhekou = round($v ['goods_price'] * $supplier_rate) / 100;
                    $zhekou_money = number_format($zhekou, 2, '.', '');
                    $cg_money += number_format($zhekou_money * $v ['goods_num'], 2, '.', '');
                }
            }
            $temp[7] = $cg_money;
            array_push($excel_data, $temp);
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    protected function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str
        );
        return $str;
    }

    public function downExcel($excel_name)
    {
        $excel_name = str_replace('.html', '', $excel_name);
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    // 下载查询的发票信息
    public function downFapiao()
    {
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $get_order = $this->db->order('create_time desc')->select();
        $new_data = [];
        if ($get_order->isEmpty()) {
            $this->layuiReturn('没有要可导出的信息', 0, 'error', 0);
        }
        $memberdb = new Memberdb();
        $cartdb = new Cartdb();
        foreach ($get_order as $key => $val) {
            $temp = [];
            $temp['out_order_no'] = $val['out_order_no'];
            $temp['order_money'] = $val['order_money'] / 100;
            $temp['caigou_invoice_duty'] = $val['caigou_invoice_duty'];
            $temp['caigou_invoice_pz'] = $val['caigou_invoice_pz'];
            $temp['hezuodanwei'] = $val['hezuodanwei'];
            $temp['caigou_state'] = $val['caigou_state'];
            $get_supplier = $memberdb->where('member_id', $val['supplier_id'])->field('supplier_name,zhuli')->find();
            $temp['supplier_name'] = $get_supplier['supplier_name'] ?: '';
            $temp['zhuli'] = $get_supplier['zhuli'] ?: '';
            $temp['cart_arr'] = $cartdb->where('order_no', $val['order_no'])
                ->with(['goods'])->select()->toArray();
            //$temp['caigou_invoice_time'] = $val['caigou_invoice_time'] ? date('Y-m-d H:i:s', $val['caigou_invoice_time']) : '未上传';
            $temp['caigou_invoice_time'] = $val['caigou_invoice_time'] ? $val['caigou_invoice_time'] : '未上传';
            $temp['supplier_rate'] = $val['supplier_rate'];
            $temp['ruku'] = $val['ruku'];
            $temp['ruku_time'] = $val['ruku_time'];
            array_push($new_data, $temp);
        }
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '发票信息' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $header_data = array(
            '订单号',
            '订单金额',
            '指派供应商',
            '来源',
            '助理',
            '采购发票状态',
            '采购发票号',
            '采购发票',
            '上传采购发票时间',
            '入库',
            '产品名称',
            '数量',
            '采购单价',
            '采购金额',
            '税务类别',
            '货品名称',
            '规格型号',
            '单位',
            '税率',
            '入库时间',
            '备注'
        );
        $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $caigou_state_arr = array(
            '1' => '审核通过',
            '2' => '待审核',
            '3' => '驳回',
            '4' => '未提交',
            '5' => '快普已提交',
            '6' => '部分开票'
        );
        $ruku_arr = array(
            '1' => '已入库',
            '2' => '未入库'
        );
        $uploaddb = new Uploaddb();
        // 添加zip
        $zip_name = 'uploads/Excel/zip/打包发票信息' . date('Ymdhi') . '.' . rand(1000, 9999) . '.zip';
        $zip = new \ZipArchive();
        $zip->open($zip_name, \ZipArchive::CREATE);
        foreach ($new_data as $key => $val) {
            // 处理文件夹名称
            $temp[0] = $val['out_order_no'];
            $temp[1] = $val['order_money'];
            $temp[2] = $val['supplier_name'];
            $temp[3] = $val['hezuodanwei'];
            $temp[4] = $val['zhuli'];
            $temp[5] = $caigou_state_arr [$val ['caigou_state']];
            $temp[6] = $val['caigou_invoice_duty'];
            $pz_arr = [];
            if ($val['caigou_invoice_pz']) {
                $get_file = $uploaddb->whereIn('upload_id', explode(',', $val['caigou_invoice_pz']))->select();
                foreach ($get_file as $k => $v) {
                    array_push($pz_arr, $v['save_path']);
                }
                $duty = explode(',', $val['caigou_invoice_duty']);
                for ($i = 0; $i < count($pz_arr); $i++) {
                    $ext = explode('.', $pz_arr[$i]);
                    $zip->addFile(str_replace('http://fen.utecbj.com/', '', $pz_arr[$i]), $duty[$i] . '-' . $i . '.' . end($ext));
                }
            }
            $temp[7] = implode(';', $pz_arr);
            //$temp[8] = $val['caigou_invoice_time'] == '未上传' ? $val['caigou_invoice_time'] : date('Y-m-d H:i:s', $val['caigou_invoice_time']);
            $temp[8] = $val['caigou_invoice_time'];
            $temp[9] = isset($ruku_arr[$val['ruku']]) ? $ruku_arr[$val['ruku']] : '其他';
            //$temp[9] = $val['ruku'];
            foreach ($val['cart_arr'] as $k => $v) {
                $temp[10] = $v['goods']['goods_name'];
                $temp[11] = $v['goods_num'];
                //$temp[8] = number_format($v['goods_price']*$val['supplier_rate'],2,'.','');
                $temp[12] = number_format(round($v ['goods_price'] * $val['supplier_rate']) / 100, 2, '.', '');
                //$temp[9] = number_format($v['goods_price']*$val['supplier_rate']*$v['goods_num'],2,'.','');
                $temp[13] = number_format(round($v ['goods_price'] * $val['supplier_rate']) * $v['goods_num'] / 100, 2, '.', '');
                $temp[14] = $v['product_area'] ?: $v['goods']['product_area'];
                $temp[15] = $v['product_firm'] ?: $v['goods']['product_firm'];
                $temp[16] = $v['invoice_model'] ?: $v['goods']['invoice_model'];
                $temp[17] = $v['goods_unit'] ?: $v['goods']['goods_unit'];
                $temp[18] = $v['goods_keywords'] ?: $v['goods']['goods_keywords'];
                $temp[19] = $val['ruku_time'];
                $temp[20] = $v['goods_beizhu3'] ?: $v['goods']['goods_beizhu3'];


                array_push($excel_data, $temp);
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBodyInvoice($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
        $obj_write->save('./uploads/Excel/zip/' . $excel_name);
        $zip->addFile('./uploads/Excel/zip/' . $excel_name, $excel_name);
        $zip->close();
        $this->layuiReturn('https://tailongji.dixintong.com/' . str_replace('./', '/', $zip_name), 1, '打包成功', 1);
    }

    protected function setExcelBodyInvoice($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 0; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 0; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    protected function setExcelHeader($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 52) {
                $cell_value = chr(66) . chr($start + ($i - 52)) . '1';
                $cell_name = chr(66) . chr($start + ($i - 52));
            } elseif ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 52) {
                $cell_value = chr(66) . chr($start + ($i - 52));
            } elseif ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 37; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 37; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    protected function setExcelBodynew($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 52) {
                $cell_value = chr(66) . chr($start + ($i - 52));
            } elseif ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 35; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 35; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }
    /**
     * Title("导出采购发票明细")
     */
    public function excelGysInvoiceAll()
    {
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        $get_order = $this->db->order('order_id desc')->select();
        if (!$get_order->isEmpty()) {
            $cartdb = new Cartdb ();
            $memberdb = new Memberdb ();
            $goodsdb = new Goodsdb ();
            $shoppingdb = new Shoppingdb ();
            $get_order = $get_order->toArray();
            $new_order = array();
            foreach ($get_order as $key => $val) {
                $temp_api = json_decode($val['api_param'], true);
                $get_order[$key]['beizhu'] = isset($temp_api['remark']) ? $temp_api['remark'] : '';
                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'] / 100;
                if ($val ['supplier_id']) {
                    $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $val ['supplier_id'])->find()->toArray();
                    $get_order [$key] ['supplier_name'] = $get_supplier ['supplier_name'];
                    $get_order [$key] ['yewuyuan'] = $get_supplier ['yewuyuan'];
                } else {
                    $get_order [$key] ['supplier_name'] = '未指定供应商';
                    $get_order [$key] ['yewuyuan'] = '';
                }
                $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $val ['order_no'])->select();
                if (!$get_cart->isEmpty()) {
                    $get_cart = $get_cart->toArray();
                    $zhekou_money = 0;
                    foreach ($get_cart as $k => $v) {
                        $zhekou_money += number_format(round($v ['goods_price'] * $val ['supplier_rate']) * $v ['goods_num'] / 100, 2, '.', '');
                        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $v ['goods_sku'])->where('site_id', SITE_ID)->find();
                        if ($get_goods) {
                            $get_cart [$k] ['goods_info'] = $get_goods->toArray();
                        }
                    }
                    $get_order [$key] ['supplier_rate_money'] = $zhekou_money;
                    $get_order [$key] ['cart_info'] = $get_cart;
                }
                $shop_info = array(
                    'contacts' => '无',
                    'phone' => '无'
                );
                if ($val ['shopping_id']) {
                    $get_shopping = $shoppingdb->useGlobalScope(false)->where('shopping_id', $val ['shopping_id'])->find();
                    if ($get_shopping) {
                        $shop_info = $get_shopping->toArray();
                    }
                }
                $get_order [$key] ['shopping_info'] = $shop_info;
                $temp = json_decode($val ['api_param'], true);
                $get_order [$key] ['citys'] = $temp ['Cityname'] . $temp ['address'];
                if ((isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') || (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes')) {
                    // 如果导出的是更换供货商 这里这不推送数据
                } else {
                    array_push($new_order, $get_order [$key]);
                }
                if (isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') {
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);
                        if ($temp_s > 1) {
                            for ($x = 0; $x < count($temp_s) - 1; $x++) {
                                $get_order [$key] ['order_state'] = -2;
                                $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                                $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                                $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                            }
                        }
                    }
                }
                if (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes') {
                    $supplier_name = '';
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);

                        if (count($temp_s) > 0) {
                            $supplier_name = $temp_s [count($temp_s) - 1] ['supplier_name'];
                        }
                    }
                    $get_order [$key] ['order_state'] = -2;
                    $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                    $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                    $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                    $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                }
            }
        }
        $data = $new_order;
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '采购发票' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '订单号',
            '订单类型',
            '单位名称',
            '纳税识别号',
            '地址、电话',
            '开户行及账号',
            '供应商',
            '税务大类',
            '税务编码',
            '商品名称',
            '开票名称',
            '规格型号',
            '数量',
            '单位',
            '采购单价（元）',
            '采购金额（元）',
            '税率',
            '备注'
        );
        $this->setExcelHeader2($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        foreach ($data as $key => $val) {
            $cg_money = 0;
            if (!isset($val ['cart_info'])) {
                continue;
            }
            foreach ($val ['cart_info'] as $k => $v) {
                if (isset($v ['goods_info']) && $v['goods_info']) {
                    unset ($temp);
                    $pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                    $supplier_rate = $val ['supplier_rate'] ? $val ['supplier_rate'] : 100;
                    $temp [0] = $val ['out_order_no'] . " ";
                    $temp [1] = $order_type_arr [$val ['order_type']];
                    $temp [2] = '北京市泰龙吉贸易有限公司';
                    $temp [3] = '91110105675715354X';
                    $temp [4] = '北京市朝阳区管庄乡杨闸村京通辅路南8号院 F1 010-59521909';
                    $temp [5] = '交通银行北京林萃路支行  110061203018010014524';
                    $temp [6] = $val ['supplier_name'];
                    $temp [7] = $v['product_area'] ?: $v['goods_info']['product_area'];
                    $temp [8] = "\t" . ($v['shuiwu_id'] ?: $v['goods_info']['shuiwu_id']);
                    $temp [9] = $v ['goods_info'] ['goods_name'];
                    $temp [10] = $v['product_firm'] ?: $v['goods_info']['product_firm'];
                    $temp [11] = $v['invoice_model'] ?: $v['goods_info']['invoice_model'];
                    $temp [12] = $v ['goods_num'];
                    $temp [13] = $v['goods_unit'] ?: $v['goods_info']['goods_unit'];
                    $zhekou = round($v ['goods_price'] * $supplier_rate) / 100;
                    $temp [14] = number_format($zhekou, 2, '.', '');
                    $temp [15] = number_format($temp [14] * $v ['goods_num'], 2, '.', '');
                    $cg_money += $temp [15];
                    $temp [16] = $v['goods_keywords'] ?: $v['goods_info']['goods_keywords'];
                    $temp [17] = $v['goods_beizhu3'] ?: $v['goods_info']['goods_beizhu3'];
                    array_push($excel_data, $temp);
                }
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody2($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel2', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function downExcel2($excel_name)
    {
        $excel_name = str_replace('.html', '', $excel_name);
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader2($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody2($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 7; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 7; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    public function lanjian()
    {
        $orderLogdb = new OrderLogdb();
        $save_log = [];
        $save_log['order_no'] = $this->post['order_no'];
        $save_log['member_id'] = MEMBER_ID;
        $save_log['view_text'] = '揽件';
        $save_log['post_json'] = $this->post;
        $orderLogdb->save($save_log);
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $this->post['order_no'])->find();
        $get_order->save(['lanjian' => 2]);
        $this->layuiReturn('success');
    }

    public function excelSaleInvoiceAll()
    {
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        $get_order = $this->db->order('order_id desc')->select();
        if (!$get_order->isEmpty()) {
            $cartdb = new Cartdb ();
            $memberdb = new Memberdb ();
            $goodsdb = new Goodsdb ();
            $invoicedb = new Invoicedb ();
            $shoppingdb = new Shoppingdb ();
            $get_order = $get_order->toArray();
            $new_order = array();
            foreach ($get_order as $key => $val) {
                $temp_api = json_decode($val['api_param'], true);
                $get_order[$key]['beizhu'] = isset($temp_api['remark']) ? $temp_api['remark'] : '';
                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'] / 100;
                if ($val ['supplier_id']) {
                    $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $val ['supplier_id'])->find()->toArray();
                    $get_order [$key] ['supplier_name'] = $get_supplier ['supplier_name'];
                    $get_order [$key] ['yewuyuan'] = $get_supplier ['yewuyuan'];
                } else {
                    $get_order [$key] ['supplier_name'] = '未指定供应商';
                    $get_order [$key] ['yewuyuan'] = '';
                }
                $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $val ['order_no'])->select();
                if (!$get_cart->isEmpty()) {
                    $get_cart = $get_cart->toArray();
                    $zhekou_money = 0;
                    foreach ($get_cart as $k => $v) {
                        $zhekou_money += number_format(round($v ['goods_price'] * $val ['supplier_rate']) * $v ['goods_num'] / 100, 2, '.', '');
                        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $v ['goods_sku'])->where('site_id', SITE_ID)->find();
                        if ($get_goods) {
                            $get_cart [$k] ['goods_info'] = $get_goods->toArray();
                        }
                    }
                    $get_order [$key] ['supplier_rate_money'] = $zhekou_money;
                    $get_order [$key] ['cart_info'] = $get_cart;
                }
                $invoice_info = array(
                    'invoice_title' => '无',
                    'invoice_duty' => '无'
                );
                if ($val ['order_no']) {
                    $get_invoice = $invoicedb->useGlobalScope(false)->where('order_nos', $val ['order_no'])->find();
                    if ($get_invoice) {
                        $invoice_info = $get_invoice->toArray();
                    }
                }
                $get_order [$key] ['invoice_info'] = $invoice_info;
                $shop_info = array(
                    'contacts' => '无',
                    'phone' => '无'
                );
                if ($val ['shopping_id']) {
                    $get_shopping = $shoppingdb->useGlobalScope(false)->where('shopping_id', $val ['shopping_id'])->find();
                    if ($get_shopping) {
                        $shop_info = $get_shopping->toArray();
                    }
                }
                $get_order [$key] ['shopping_info'] = $shop_info;
                $temp = json_decode($val ['api_param'], true);
                $get_order [$key] ['citys'] = $temp ['Cityname'] . $temp ['address'];
                if ((isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') || (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes')) {
                    // 如果导出的是更换供货商 这里这不推送数据
                } else {
                    array_push($new_order, $get_order [$key]);
                }
                if (isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') {
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);
                        if ($temp_s > 1) {
                            for ($x = 0; $x < count($temp_s) - 1; $x++) {
                                $get_order [$key] ['order_state'] = -2;
                                $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                                $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                                $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                            }
                        }
                    }
                }
                if (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes') {
                    $supplier_name = '';
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);

                        if (count($temp_s) > 0) {
                            $supplier_name = $temp_s [count($temp_s) - 1] ['supplier_name'];
                        }
                    }
                    $get_order [$key] ['order_state'] = -2;
                    $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                    $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                    $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                    $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                }
            }
        }
        $data = $new_order;
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '销售发票' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '订单号',
            '订单类型',
            '单位名称',
            '纳税识别号',
            '联系电话',
            '税务大类',
            '税务编码',
            '商品名称',
            '开票名称',
            '规格型号',
            '数量',
            '单位',
            '销售单价（元）',
            '销售金额（元）'
        );
        $this->setExcelHeader3($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        foreach ($data as $key => $val) {
            $cg_money = 0;
            if (!isset($val ['cart_info'])) {
                continue;
            }
            foreach ($val ['cart_info'] as $k => $v) {
                if (isset($v ['goods_info']) && $v['goods_info']) {
                    unset ($temp);
                    $pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                    $supplier_rate = $val ['supplier_rate'] ? $val ['supplier_rate'] : 100;
                    $temp [0] = $val ['out_order_no'] . " ";
                    $temp [1] = $order_type_arr [$val ['order_type']];
                    $temp [2] = $val ['invoice_info'] ['invoice_title'];
                    $temp [3] = $val ['invoice_info'] ['invoice_duty'] . " ";
                    $temp [4] = $val ['shopping_info'] ['phone'] . " ";
                    $temp [5] = $v['product_area'] ?: $v['goods_info']['product_area'];
                    $temp [6] = "\t" . ($v['shuiwu_id'] ?: $v['goods_info']['shuiwu_id']);
                    $temp [7] = $v ['goods_info'] ['goods_name'];
                    $temp [8] = $v['product_firm'] ?: $v['goods_info']['product_firm'];
                    $temp [9] = $v['invoice_model'] ?: $v['goods_info']['invoice_model'];
                    $temp [10] = $v ['goods_num'];
                    $temp [11] = $v['goods_unit'] ?: $v['goods_info']['goods_unit'];
                    $temp [12] = $v ['goods_price'];
                    $temp [13] = number_format($v ['goods_price'] * $v ['goods_num'], 2, '.', '');
                    array_push($excel_data, $temp);
                }
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody3($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel3', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function downExcel3($excel_name)
    {
        $excel_name = str_replace('.html', '', $excel_name);
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader3($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody3($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 5; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 5; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

// 导出入库表
    public function rukuWhereExportOrder()
    {
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        /*$get_order = $this->db
            ->whereIn('apply_state', [2, 3, 4])
            ->where('opinion', '线下开票')
            ->where('order_type', '<>', 7)
            ->where('order_type', 5)
            ->where('invoice_state', 1)
            ->order('order_id desc')->select();*/
        /*$start_time = strtotime(date('Y-m-d', strtotime('-1 day')));
        $end_time = strtotime(date('Y-m-d'));*/
        $start_time = strtotime(date('Y-m-d', strtotime('-1 day')));
        $end_time = strtotime(date('Y-m-d'));
        if (isset($this->post['apply_time_start']) && $this->post['apply_time_start']) {
            $start_time = strtotime($this->post['apply_time_start']);
            $end_time = strtotime($this->post['apply_time_end']);
        }
        //$base_sql = "SELECT * FROM ys_order WHERE site_id = 117 AND gys_fh_state = 1 AND ruku = 2 AND apply_time >" . $start_time . " and apply_time<" . $end_time . " AND (apply_state NOT IN (1,4) OR (apply_state = 4 AND returncode = '线下开具成功'))";
        $base_sql = "SELECT * FROM ys_order WHERE site_id = 117 AND gys_fh_state = 1 AND ruku = 2 AND apply_time >" . $start_time . " and apply_time<" . $end_time . " AND (apply_state NOT IN (1,4) OR (apply_state = 4 AND nopass_info = '线下开票'))";
        //  $base_sql = "SELECT * FROM ys_order WHERE site_id = 117 AND gys_fh_state = 1 AND ruku = 2 AND apply_time >" . $start_time . " and apply_time<" . $end_time . " AND apply_state <> 1";
        $sql = "SELECT * FROM (" . $base_sql . ") o WHERE order_type NOT IN (5,7) OR (order_type = 5 AND invoice_state = 2)";
        $get_order = Db::query($sql);
        $new_order = [];
        if ($get_order) {
            $cartdb = new Cartdb ();
            $memberdb = new Memberdb ();
            $goodsdb = new Goodsdb ();
            $shoppingdb = new Shoppingdb ();
            //$get_order = $get_order->toArray();
            $new_order = array();
            foreach ($get_order as $key => $val) {
                $temp_api = json_decode($val['api_param'], true);
                $get_order[$key]['beizhu'] = isset($temp_api['remark']) ? $temp_api['remark'] : '';
                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'] / 100;
                if ($val ['supplier_id']) {
                    $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $val ['supplier_id'])->find()->toArray();
                    $get_order [$key] ['company_name'] = $get_supplier ['company_name'];
                    $get_order [$key] ['yewuyuan'] = $get_supplier ['yewuyuan'];
                } else {
                    $get_order [$key] ['company_name'] = '未指定供应商';
                    $get_order [$key] ['yewuyuan'] = '';
                }
                $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $val ['order_no'])->select();
                if (!$get_cart->isEmpty()) {
                    $get_cart = $get_cart->toArray();
                    $zhekou_money = 0;
                    foreach ($get_cart as $k => $v) {
                        $zhekou_money += number_format(round($v ['goods_price'] * $val ['supplier_rate']) * $v ['goods_num'] / 100, 2, '.', '');
                        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $v ['goods_sku'])->where('site_id', SITE_ID)->find();
                        if ($get_goods) {
                            $get_cart [$k] ['goods_info'] = $get_goods->toArray();
                        }
                    }
                    $get_order [$key] ['supplier_rate_money'] = $zhekou_money;
                    $get_order [$key] ['cart_info'] = $get_cart;
                }
                $shop_info = array(
                    'contacts' => '无',
                    'phone' => '无'
                );
                if ($val ['shopping_id']) {
                    $get_shopping = $shoppingdb->useGlobalScope(false)->where('shopping_id', $val ['shopping_id'])->find();
                    if ($get_shopping) {
                        $shop_info = $get_shopping->toArray();
                    }
                }
                $get_order [$key] ['shopping_info'] = $shop_info;
                $temp = json_decode($val ['api_param'], true);
                $get_order [$key] ['citys'] = $temp ['Cityname'] . $temp ['address'];
                if ((isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') || (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes')) {
                    // 如果导出的是更换供货商 这里这不推送数据
                } else {
                    array_push($new_order, $get_order [$key]);
                }
                if (isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') {
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);
                        if ($temp_s > 1) {
                            for ($x = 0; $x < count($temp_s) - 1; $x++) {
                                $get_order [$key] ['order_state'] = -2;
                                $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                                $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                                $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                            }
                        }
                    }
                }
                if (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes') {
                    $supplier_name = '';
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);

                        if (count($temp_s) > 0) {
                            $supplier_name = $temp_s [count($temp_s) - 1] ['supplier_name'];
                        }
                    }
                    $get_order [$key] ['order_state'] = -2;
                    $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                    $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                    $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                    $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                }
            }
        }
        $data = $new_order;
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '昨日入库表' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '军采单号',
            '订单金额',
            '采购金额',
            '订单类型',
            '供应商发货时间',
            '发票申请',
            '发票申请时间',
            '入库',
            '收货地址',
            '收货人',
            '收货人电话',
            '指定供应商',
            '折扣率',
            '商品信息',
            '产品编号',
            '型号',
            '军网编号',
            '产品编号（D）',
            '迪信通系统名称（D）',
            '税务大类',
            '开票名称',
            '规格型号',
            '单位',
            '购买数量',
            '销售价',
            '销售小计',
            '采购价',
            '采购小计'
        );
        $this->setExcelHeader4($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        $apply_state_arr = array(
            '1' => '未提交',
            '2' => '等待审核',
            '3' => '审核通过',
            '4' => '驳回'
        );
        $ruku_arr = array(
            '1' => '已入库',
            '2' => '未入库'
        );
        foreach ($data as $key => $val) {
            $cg_money = 0;
            if (!isset($val ['cart_info'])) {
                continue;
            }
            foreach ($val ['cart_info'] as $k => $v) {
                if (isset($v ['goods_info']) && $v['goods_info']) {
                    unset ($temp);
                    $pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                    $supplier_rate = $val ['supplier_rate'] ? $val ['supplier_rate'] : 100;
                    $temp [0] = $val ['out_order_no'] . " ";
                    $temp [1] = $val ['order_money'];
                    $temp [2] = number_format($val ['supplier_rate_money'], 2, '.', '');
                    $temp [3] = $order_type_arr [$val ['order_type']];
                    $temp [4] = $val ['gys_fh_time'] ? date('Y-m-d H:i:s', $val ['gys_fh_time']) : '';
                    $temp [5] = $apply_state_arr [$val ['apply_state']] . ' ' . $val ['returncode'];
                    $temp [6] = $val ['apply_time'] ? date('Y-m-d H:i:s', $val ['apply_time']) : '';
                    $temp [7] = $ruku_arr [$val ['ruku']];
                    $temp [8] = $val ['citys'];
                    $temp [9] = $val ['shopping_info'] ['contacts'];
                    $temp [10] = $val ['shopping_info'] ['phone'] . " ";
                    $temp [11] = $val ['company_name'];
                    $temp [12] = $supplier_rate . '%';
                    $temp [13] = $v ['goods_info'] ['goods_name'];
                    $temp [14] = $v ['goods_sku'];
                    $temp [15] = $v ['goods_info']['goods_model'] ?? '';
                    $temp [16] = $v ['goods_info'] ['jun_id'];
                    $temp [17] = $v ['goods_info'] ['upc'] . " ";
                    $temp [18] = $v ['goods_info'] ['goods_son_name'];
                    $temp [19] = $v['product_area'] ?: $v['goods_info']['product_area'];
                    $temp [20] = $v['product_firm'] ?: $v['goods_info']['product_firm'];
                    $temp [21] = $v['invoice_model'] ?: $v['goods_info']['invoice_model'];
                    $temp [22] = $v['goods_unit'] ?: $v['goods_info']['goods_unit'];
                    $temp [23] = $v ['goods_num'];
                    $temp [24] = $v ['goods_price'];
                    $temp [25] = number_format($v ['goods_price'] * $v ['goods_num'], 2, '.', '');
                    $zhekou = round($v ['goods_price'] * $supplier_rate) / 100;
                    $temp [26] = number_format($zhekou, 2, '.', '');
                    $temp [27] = number_format($temp [26] * $v ['goods_num'], 2, '.', '');
                    $cg_money += $temp [27];
                    array_push($excel_data, $temp);
                }
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody5($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel5', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function downExcel5($excel_name)
    {
        $excel_name = str_replace('.html', '', $excel_name);
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader5($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody5($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 13; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 13; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }


    /**
     * Title("根据导入的订单号导出入库表")
     */
    public function exportRukuOfOrderXsl()
    {
        set_time_limit(0);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $get_col_num = $sheet->getHighestColumn(); // 总列
                $phpexcel_shared_date = new \PHPExcel_Shared_Date ();
                $the_sheet = $objPHPExcel->getActiveSheet();
                $array_temp = [];
                for ($i = 2; $i <= $get_row_num; $i++) {
                    array_push($array_temp, $this->getSheetValue($the_sheet, "A" . $i));
                }
                $this->db->param['out_order_no'] = $array_temp;
                $this->rukuexportOrder();
            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 0);
            }
        }
    }


    /**
     * Title("导出入库表")
     */
    public function rukuexportOrder()
    {
        set_time_limit(0);
        ini_set('memory_limit', '4096M');
        $get_order = $this->db->order('order_id desc')->select();
        if (!$get_order->isEmpty()) {
            $cartdb = new Cartdb ();
            $memberdb = new Memberdb ();
            $goodsdb = new Goodsdb ();
            $shoppingdb = new Shoppingdb ();
            $get_order = $get_order->toArray();
            $new_order = array();
            foreach ($get_order as $key => $val) {
                $temp_api = json_decode($val['api_param'], true);
                $get_order[$key]['beizhu'] = isset($temp_api['remark']) ? $temp_api['remark'] : '';
                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'] / 100;
                if ($val ['supplier_id']) {
                    $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $val ['supplier_id'])->find()->toArray();
                    $get_order [$key] ['supplier_name'] = $get_supplier ['supplier_name'];
                    $get_order [$key] ['yewuyuan'] = $get_supplier ['yewuyuan'];
                } else {
                    $get_order [$key] ['supplier_name'] = '未指定供应商';
                    $get_order [$key] ['yewuyuan'] = '';
                }
                $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $val ['order_no'])->select();
                if (!$get_cart->isEmpty()) {
                    $get_cart = $get_cart->toArray();
                    $zhekou_money = 0;
                    foreach ($get_cart as $k => $v) {
                        $zhekou_money += number_format(round($v ['goods_price'] * $val ['supplier_rate']) * $v ['goods_num'] / 100, 2, '.', '');
                        $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $v ['goods_sku'])->where('site_id', SITE_ID)->find();
                        if ($get_goods) {
                            $get_cart [$k] ['goods_info'] = $get_goods->toArray();
                        }
                    }
                    $get_order [$key] ['supplier_rate_money'] = $zhekou_money;
                    $get_order [$key] ['cart_info'] = $get_cart;
                }
                $shop_info = array(
                    'contacts' => '无',
                    'phone' => '无'
                );
                if ($val ['shopping_id']) {
                    $get_shopping = $shoppingdb->useGlobalScope(false)->where('shopping_id', $val ['shopping_id'])->find();
                    if ($get_shopping) {
                        $shop_info = $get_shopping->toArray();
                    }
                }
                $get_order [$key] ['shopping_info'] = $shop_info;
                $temp = json_decode($val ['api_param'], true);
                $get_order [$key] ['citys'] = $temp ['Cityname'] . $temp ['address'];
                if ((isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') || (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes')) {
                    // 如果导出的是更换供货商 这里这不推送数据
                } else {
                    array_push($new_order, $get_order [$key]);
                }
                if (isset ($this->post ['is_reset']) && $this->post ['is_reset'] == 'yes') {
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);
                        if ($temp_s > 1) {
                            for ($x = 0; $x < count($temp_s) - 1; $x++) {
                                $get_order [$key] ['order_state'] = -2;
                                $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                                $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                                $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                                $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                                $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                                $get_order [$key] ['supplier_name'] = $temp_s [$x] ['supplier_name'];
                                array_push($new_order, $get_order [$key]);
                            }
                        }
                    }
                }
                if (isset ($this->post ['is_feizhi']) && $this->post ['is_feizhi'] == 'yes') {
                    $supplier_name = '';
                    if ($val ['reset_suppler']) {
                        $temp_s = json_decode($val ['reset_suppler'], true);

                        if (count($temp_s) > 0) {
                            $supplier_name = $temp_s [count($temp_s) - 1] ['supplier_name'];
                        }
                    }
                    $get_order [$key] ['order_state'] = -2;
                    $get_order [$key] ['out_order_no'] = $get_order [$key] ['out_order_no'] . '_add';
                    $get_order [$key] ['order_money'] = $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                    $get_order [$key] ['out_order_no'] = str_replace('_add', '_diff', $get_order [$key] ['out_order_no']);
                    $get_order [$key] ['order_money'] = 0 - $get_order [$key] ['order_money'];
                    $get_order [$key] ['supplier_rate_money'] = 0 - $get_order [$key] ['supplier_rate_money'];
                    $get_order [$key] ['supplier_name'] = '';
                    array_push($new_order, $get_order [$key]);
                }
            }
        }
        $data = $new_order;
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        ob_end_clean();
        $excel_name = '入库表' . date('Ymdhi') . '.' . rand(1000, 9999) . '.xls';
        $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
        $obj_act_sheet = $phpExcel->getActiveSheet();
        $i = 1;
        $header_data = array(
            '军采单号',
            '订单类型',
            '订单金额',
            '采购金额',
            '收货地址',
            '收货人',
            '收货人电话',
            '折扣率',
            '指定供应商',
            '供应商发货时间',
            '供应商收货时间',
            '订单产品',
            '产品编号',
            '型号',
            '军网编号',
            'D名称',
            'D编号',
            '购买数量',
            '销售金额',
            '小计',
            '采购价',
            '采购小计',
            '税务大类',
            '税务编码',
            '开票名称',
            '规格型号',
            '单位'
        );
        $this->setExcelHeader4($obj_act_sheet, $phpExcel, $header_data);
        $excel_data = array();
        $order_type_arr = array(
            '1' => '自然订单',
            '2' => '报备订单',
            '3' => '其他',
            '4' => '改供货商',
            '5' => '退货',
            '6' => '竞价订单',
            '7' => '废止订单',
            '8' => '前报备',
            '9' => '后报备',
            '10' => '带量竞价'
        );
        foreach ($data as $key => $val) {
            $cg_money = 0;
            if (!isset($val ['cart_info'])) {
                continue;
            }
            foreach ($val ['cart_info'] as $k => $v) {
                if (isset($v ['goods_info']) && $v['goods_info']) {
                    unset ($temp);
                    $pay_type = $val ['pay_type'] ? $val ['pay_type'] : 1;
                    $supplier_rate = $val ['supplier_rate'] ? $val ['supplier_rate'] : 100;
                    $temp [0] = $val ['out_order_no'] . " ";
                    $temp [1] = $order_type_arr [$val ['order_type']];
                    $temp [2] = $val ['order_money'];
                    $temp [3] = number_format($val ['supplier_rate_money'], 2, '.', '');
                    $temp [4] = $val ['citys'];
                    $temp [5] = $val ['shopping_info'] ['contacts'];
                    $temp [6] = $val ['shopping_info'] ['phone'] . " ";
                    $temp [7] = $supplier_rate . '%';
                    $temp [8] = $val ['supplier_name'];
                    $temp [9] = $val ['gys_fh_time'] ? $val ['gys_fh_time'] : '';
                    $temp [10] = $val ['gys_sh_time'] ? $val ['gys_sh_time'] : '';
                    $temp [11] = $v ['goods_info'] ['goods_name'];
                    $temp [12] = $v ['goods_sku'];
                    $temp [13] = $v ['goods_info']['goods_model'] ?? '';
                    $temp [14] = $v ['goods_info'] ['jun_id'];
                    $temp [15] = $v ['goods_info'] ['goods_son_name'];
                    $temp [16] = $v ['goods_info'] ['upc'] . " ";
                    $temp [17] = $v ['goods_num'];
                    $temp [18] = $v ['goods_price'];
                    $temp [19] = number_format($v ['goods_price'] * $v ['goods_num'], 2, '.', '');
                    $zhekou = round($v ['goods_price'] * $supplier_rate) / 100;
                    $temp [20] = number_format($zhekou, 2, '.', '');
                    $temp [21] = number_format($temp [20] * $v ['goods_num'], 2, '.', '');
                    $cg_money += $temp [21];
                    $temp [22] = $v['product_area'] ?: $v['goods_info']['product_area'];
                    $temp [23] = "\t" . ($v['shuiwu_id'] ?: $v['goods_info']['shuiwu_id']);
                    $temp [24] = $v['product_firm'] ?: $v['goods_info']['product_firm'];
                    $temp [25] = $v['invoice_model'] ?: $v['goods_info']['invoice_model'];
                    $temp [26] = $v['goods_unit'] ?: $v['goods_info']['goods_unit'];
                    array_push($excel_data, $temp);
                }
            }
        }
        $vAlign = new \PHPExcel_Style_Alignment ();
        $this->setExcelBody4($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);

        $obj_write->save('./uploads/Excel/' . $excel_name);
        $all_path = $excel_name;
        $this->layuiReturn(url('Order/downExcel4', array(
            'excel_name' => $all_path
        )), 1, '导出成功', 1);
    }

    public function downExcel4($excel_name)
    {
        $excel_name = str_replace('.html', '', $excel_name);
        $path_excel_name = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/' . $excel_name;
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename=' . $excel_name . '');
        header("Content-Transfer-Encoding:binary");
        readfile($path_excel_name);
    }

    protected function setExcelHeader4($obj_act_sheet, $phpExcel, $data)
    {
        $start = 65;
        for ($i = 0; $i < count($data); $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26)) . '1';
                $cell_name = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i) . '1';
                $cell_name = chr($start + $i);
            }
            $obj_act_sheet->setCellValue($cell_value, $data [$i]);
            $phpExcel->getActiveSheet()->getColumnDimension($cell_name)->setWidth(20);
        }
    }

    protected function setExcelBody4($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 11; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 11; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    protected function setExcelBody6($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, $val [$i]);
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // return true;
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 5; $y++) {
                        $cell_value = chr($start + $y);
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 4; $y++) {
                $cell_value = chr($start + $y);
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }

    // 查询订单是否存在

    public function searchOrderNo()
    {
        $get_order_nos = explode('<br />', nl2br($this->post['order_nos']));
        $new_order = [];
        foreach ($get_order_nos as $key => $val) {
            array_push($new_order, trim($val));
        }
        $result = [];
        if (count($new_order) > 0) {
            $get_order_nos = $this->db
                ->useGlobalScope(false)
                ->whereIn('out_order_no', $new_order)
                ->select();
            for ($i = 0; $i < count($new_order); $i++) {
                $temp = [];
                $temp['out_order_no'] = $new_order[$i];
                $temp['flag'] = false;
                foreach ($get_order_nos as $key => $val) {
                    if ($new_order[$i] == $val['out_order_no']) {
                        $temp['flag'] = true;
                        $temp['order_info'] = $val;
                        $temp['order_no'] = $val['order_no'];
                    }
                }
                array_push($result, $temp);
            }
        }
        $this->layuiReturn($result);
    }

    public function detail()
    {
        if (isset ($this->post ['site_id'])) {
            $site_id = $this->post ['site_id'];
        } else {
            $site_id = SITE_ID;
        }
        $this->assign('site_id', $site_id);
        $this->db->param ['need_pay_info'] = 'yes';
        $this->db->param ['need_supplier'] = 'yes';
        $this->db->param['need_cart'] = 'yes';
        $return = $this->db->ajaxFind();


        $goodsdb = new Goodsdb ();
        $err_flag = false;
        foreach ($return ['cart_info'] ['list'] as $key => $val) {
            $get_goods = $goodsdb->where('goods_sku', $val ['goods_sku'])->find();
            if ($get_goods) {
                $get_goods = $get_goods->toArray();
                $return ['cart_info'] ['list'] [$key] ['goods_info'] = $get_goods;
            } else {
                print_r($val['goods_sku']);
                $err_flag = true;
            }
        }
        if ($err_flag)
            exit('以上商品错误');

        // 处理上次指派的供应商
        $temp_s = json_decode($return ['api_param'], true);
        $this->assign('jun_param', $temp_s);
        $chk_s = $this->db->useGlobalScope(false)
            //->where('api_param', 'like', '%' . $temp_s ['mobile'] . '%')
            ->where('phone', $return['phone'])
            ->where('supplier_id', '>', 0)
            ->order('order_id desc')
            ->find();
        $last_supplier = '未指派过供应商';
        if ($chk_s) {
            $chk_s = $chk_s->toArray();
            $memberdb = new Memberdb ();
            $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $chk_s ['supplier_id'])->find();
            if ($get_supplier) {
                $get_supplier = $get_supplier->toArray();
                $last_supplier = $get_supplier ['supplier_name'];
            }
        }

        $this->assign('last_supplier', $last_supplier);

        // 处理曾经指派的供应商列表
        $get_supplier_list = [];
        if ($return['phone'] != null) {
            $chk_list = $this->db->useGlobalScope(false)
                //->where('api_param', 'like', '%' . $temp_s ['mobile'] . '%')
                ->where('phone', $return['phone'])
                ->where('supplier_id', '>', 0)
                ->where('supplier_id', '<>', 10602)// 曾经指派绕过代采公司
                ->order('order_id desc')
                ->column('supplier_id');

            if ($chk_list) {
                $memberdb = new Memberdb ();
                $get_list = $memberdb->useGlobalScope(false)->whereIn('member_id', $chk_list)->select();
                if (!$get_list->isEmpty()) {
                    $get_supplier_list = $get_list->toArray();
                }
            }
        }
        $this->assign('supplier_list', $get_supplier_list);

        if (!$return) {
            exit ('订单错误');
        }
        $return ['invoice_info_list'] = $return ['invoice_info'];
        if (count($return ['invoice_info']) == 1 && (SITE_ID == 10 || SITE_ID == 13)) {
            $return ['invoice_info'] = $return ['invoice_info'] [0];
            $return ['invoice_info_json'] = json_encode($return ['invoice_info']);
        }

        // 验证品牌是否固定供应商
        $get_brand_id = Db::name('goods')->whereIn('goods_sku', $return ['cart_info']['cart_ids'])->column('jun_brandid');
        $get_brand_sign = Db::name('brand_api')->whereIn('option', $get_brand_id)->column('brand_sign');
        $get_fixed = Db::name('brand')
            ->whereIn('brand_sign', $get_brand_sign)
            ->group('fixed_supplier')
            ->column('fixed_supplier');
        $fixed_arr = array_filter($get_fixed, function ($item) {
            return !empty($item);
        });
        $memberdb = new Memberdb ();
        $supplier_field = 'member_id,supplier_rate,supplier_name';
        if (count($fixed_arr)) {
            // 全局固定供应商
            $global_fixed = [594, 601, 918, 10324, 10325, 10396, 10466, 10635, 10636];
            foreach ($fixed_arr as $key => $val) {
                $temp_val = explode(',', $val);
                foreach ($temp_val as $k => $v) {
                    array_push($global_fixed, $v);
                }
            }
            $get_supplier = $memberdb
                ->whereIn('member_id', $global_fixed)
                ->where('is_supplier', 1)
                ->where('supplier_grade', 1)
                ->field($supplier_field)
                ->order('member_id desc')->select();
        } else {
            $get_supplier = $memberdb
                ->where('is_supplier', 1)
                ->where('supplier_grade', 1)
                ->field($supplier_field)
                ->order('member_id desc')->select();
        }

        if ($get_supplier) {
            $get_supplier = $get_supplier->toArray();
        } else {
            $get_supplier = [];
        }
        $return['api_param_arr'] = json_decode($return['api_param'], true);
        $this->assign('get_supplier', $get_supplier);
        $this->assign('get_supplier_json', json_encode($get_supplier));
        $this->assign('goods_cols_invoice', json_encode($this->goods_cols_invoice));
        $this->assign('goods_cols_invoice_old', json_encode($this->goods_cols_invoice_old));
        $this->assign('data', $return);
        switch ($return ['order_state']) {
            case '1' :
                $this->assign('goods_cols', json_encode($this->goods_cols));
                break;
            case '2' :
                $this->assign('goods_cols', json_encode($this->goods_cols_state2));
                break;
            case '3' :
            case '4' :
            case '5' :
                if ($return ['shopping_state'] == 2) {
                    unset ($this->goods_cols_state2 [0]);
                }
                array_push($this->goods_cols_state2, array(
                    'width' => 130,
                    'toolbar' => '#returned_tool',
                    'field' => 'returned',
                    'title' => '退换货'
                ));
                $this->assign('goods_cols', json_encode($this->goods_cols_state2));
                // 查找安装服务产品
                $cartdb = new Cartdb ();
                $cartdb->param ['order_no'] = $return ['order_no'];
                $cartdb->param ['pack_state'] = 1;
                $cartdb->param ['is_install'] = 1;
                $cartdb->param ['need_goods_info'] = 'yes';
                $is_install = $cartdb->ajaxList();
                $this->assign('is_install', $is_install);
                break;
            default :
                $this->assign('goods_cols', json_encode($this->goods_cols_state2));
                break;
        }
        $this->assign('order_out_goods', json_encode($this->order_out_goods));
        if ($return ['order_state'] > 2) {
            // 调用发货信息
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $return ['order_no'];
            $express_list = $expressdb->ajaxList();
            $this->assign('express_list', $express_list);
        }

        // 验证推送物流信息是否完成
        $runsdb = new Runsdb();
        $chk_runs_over = $runsdb
            ->where('order_no', $return['order_no'])
            ->where('state', 2)
            ->count();
        $this->assign('chk_runs_over', $chk_runs_over);
        // 调用快递100返回的信息
        $postwuliuDb = new Postwuliudb();
        $get_wuliu = $postwuliuDb->where('order_id', $return['order_id'])->order('postwuliu_id', 'desc')->find();
        $kuaidi = [];
        $kuaidi['nu'] = '';
        $kuaidi['data'] = [];
        if ($get_wuliu) {
            $get_wuliu_param = json_decode($get_wuliu['post_json'], true);
            $get_wuliu_data = json_decode($get_wuliu_param['param'], true);
            $kuaidi = $get_wuliu_data['lastResult'];
        }
        $this->assign('kuaidi', $kuaidi);
        $this->assign('select_goods_cols', json_encode($this->select_goods_cols));
        // 调用日志
        $orderLogdb = new OrderLogdb ();
        $orderLogdb->param ['order_no'] = $this->post ['order_no'];
        $get_log = $orderLogdb->ajaxList();
        $this->assign('order_log', $get_log);
        $order_state_arr = ['无效订单', '待确认', '待发货', '待支付', '待收货', '已完成', '已退货', '已取消', '待妥投', '已废止'];
        $this->assign('orderStateArr', $order_state_arr);
        // 客服提醒
        $orderRemarkdb = new OrderRemarkdb();
        $get_remark = $orderRemarkdb
            ->where('order_no', $this->post['order_no'])
            ->where('remark_type', 2)
            ->order('create_time', 'desc')->select();
        $this->assign('orderRemarkBeizhu', $get_remark);
        $orderRemarkdb = new OrderRemarkdb();
        $get_remark = $orderRemarkdb
            ->where('order_no', $this->post['order_no'])
            ->where('remark_type', 1)
            ->order('create_time', 'desc')->select();
        $this->assign('orderRemark', $get_remark);
        return $this->fetch();
    }

    // 提前收货
    public function tiqian()
    {
        $runsdb = new Runsdb();
        $get_runs = $runsdb->where('order_no', $this->post['order_no'])->order('runs_id', 'desc')->select();
        $state_num = 0;
        if (count($get_runs) < 7) {
            $this->layuiReturn('推送信息错误，需要技术检查！');
        }
        foreach ($get_runs as $key => $val) {
            if ($val['state'] == 2) {
                $state_num++;
            }
        }
        if ($state_num == 2) {
            $base_time = $get_runs[2]['time'] ?? 0;
            $push_time = time();
            if ($push_time - $base_time < 30 * 60) {
                $this->layuiReturn('基础物流信息推送完成未到30分钟，30分钟后再提前收货');
            }
            $get_runs_8 = $runsdb->find($get_runs[1]['runs_id']);
            $info_8 = json_decode($get_runs_8['info'], true);
            $info_8 = array_splice($info_8[0], 0);
            $info_8['operateTime'] = date('Y-m-d H:i:s', time());
            $new_arr = array($info_8);
            $save_8 = ['times' => time(), 'info' => json_encode($new_arr)];
            $get_runs_8->save($save_8);
            $get_runs_9 = $runsdb->find($get_runs[0]['runs_id']);
            $time_9 = time() + 20 * 60;
            $info_9 = json_decode($get_runs_9['info'], true);
            $info_9 = array_splice($info_9[0], 0);
            $info_9['operateTime'] = date('Y-m-d H:i:s', $time_9);
            $new_arr = array($info_9);
            $save_9 = ['times' => $time_9, 'info' => json_encode($new_arr)];
            $get_runs_9->save($save_9);
            $this->layuiReturn('该订单将在20分钟后可以收货');
        } else {
            if ($state_num < 2) {
                $get_runs_9 = $runsdb->where('order_no', $this->post['order_no'])->order('runs_id', 'desc')->find();
                $time_9 = time() + 20 * 60;
                $info_9 = json_decode($get_runs_9['info'], true);
                $info_9 = array_splice($info_9[0], 0);
                $info_9['operateTime'] = date('Y-m-d H:i:s', $time_9);
                $new_arr = array($info_9);
                $save_9 = ['times' => $time_9, 'info' => json_encode($new_arr)];
                $get_runs_9->save($save_9);
                $this->layuiReturn('该订单将在20分钟后可以收货');
            } else {
                $this->layuiReturn('基础物流信息未推送完成，不能提前收货');
            }

        }
    }

    public function zipDown($out_order_no)
    {
        $zip_name = 'uploads/Excel/hetong/' . $out_order_no . '.zip';
        $zip = new \ZipArchive ();
        $res = $zip->open($zip_name, \ZipArchive::CREATE);
        if ($res === true) {
            $orderdb = new Orderdb ();
            $get_order = $orderdb->useGlobalScope(false)->where('out_order_no', $out_order_no)->find();
            if ($get_order) {
                $get_order = $get_order->toArray();
                if ($get_order ['cght']) {
                    $zip->addFile(str_replace($this->base_url, '', $get_order ['cght']));
                }
            }
        } else {
            print_r('创建失败');
        }
        $zip->close();
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zip_name));
        header("Content-Disposition: attachment; filename=\"" . basename($zip_name) . "\"");
        readfile($zip_name);
        @unlink($zip_name);
    }

    public function zipDownOne($out_order_no)
    {
        $zip_name = 'uploads/Excel/hetong/' . $out_order_no . '.zip';
        $zip = new \ZipArchive ();
        $res = $zip->open($zip_name, \ZipArchive::CREATE);
        if ($res === true) {
            $orderdb = new Orderdb ();
            $get_order = $orderdb->useGlobalScope(false)->where('out_order_no', $out_order_no)->find();
            if ($get_order) {
                $get_order = $get_order->toArray();
                if ($get_order ['cght']) {
                    $zip->addFile('uploads/Excel/hetong/' . $out_order_no . '采购合同.pdf', $out_order_no . '采购合同.pdf');
                }
            }
        } else {
            print_r('创建失败');
        }
        $zip->close();
        // readfile ( $zip_name );
        return './' . $zip_name;
    }

    public function zipDownAll($out_order_no)
    {
        $out_order_no = explode(',', $out_order_no);
        $zip_name = 'uploads/Excel/hetong/' . date('YmdHis') . rand(100, 999) . '.zip';
        $file_name_arr = array();
        $zip_all = new \ZipArchive ();
        $res = $zip_all->open($zip_name, \ZipArchive::CREATE);
        if ($res === true) {
            foreach ($out_order_no as $key => $val) {
                $file_name = $this->zipDownOne($val);
                $zip_all->addFile($file_name);
                array_push($file_name_arr, $file_name);
            }
        } else {
            halt('错误');
        }
        $zip_all->close();
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: Binary");
        header("Content-Length: " . filesize($zip_name));
        header("Content-Disposition: attachment; filename=\"" . basename($zip_name) . "\"");
        readfile($zip_name);
        @unlink($zip_name);
        foreach ($file_name_arr as $key => $val) {
            @unlink($val);
        }
    }

    public function combjd()
    {
        $offerdb = new Offerdb ();
        $offerdb->param ['audit_state'] = 1;
        $offerdb->param ['is_used'] = 2;
        $offerdb->param ['page'] = 1;
        $offerdb->param ['limit'] = 50;
        $get_offer = $offerdb->ajaxList();
        if (count($get_offer) == 0) {
            $this->layuiReturn('', 0, '暂无报价单', 0);
        } else {
            $cartdb = new Cartdb ();
            $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $this->post ['order_no'])->select();
            if ($get_cart) {
                $get_cart = $get_cart->toArray();
                $score_arr = array();
                $cart_num = count($get_cart);
                $result_arr = array();
                foreach ($get_offer as $b => $s) {
                    $temp ['offer_id'] = $s ['offer_id'];
                    $temp ['supplier_name'] = $s ['supplier_name'];
                    $temp ['create_time'] = $s ['create_time'];
                    $temp ['supplier_id'] = $s ['supplier_id'];
                    $temp ['like_precent'] = 0;
                    foreach ($s ['param_arr'] as $key => $val) {
                        foreach ($get_cart as $k => $v) {
                            if ($val ['goods_sku'] == $v ['goods_sku']) {
                                if ($val ['api_price'] != $v ['goods_price']) {
                                    $temp ['like_precent'] = $temp ['like_precent'] + 0.5 / $cart_num;
                                } else {
                                    $temp ['like_precent'] = $temp ['like_precent'] + 1 / $cart_num;
                                }
                            }
                        }
                    }
                    if (count($s ['param_arr']) != $cart_num) {
                        $temp ['like_precent'] = $temp ['like_precent'] - abs(count($s ['param_arr']) - $cart_num) / $cart_num;
                    }
                    array_push($result_arr, $temp);
                }
                $new_arr = array();
                foreach ($result_arr as $key => $val) {
                    if ($val ['like_precent'] >= 0.5) {
                        $val ['like_precent'] = round($val ['like_precent'] * 100);
                        array_push($new_arr, $val);
                    }
                }
                $com_arr = array_column($new_arr, 'like_precent');
                array_multisort($com_arr, SORT_DESC, $new_arr);
                $this->layuiReturn($new_arr, count($com_arr), 'success', 1);
            } else {
                $this->layuiReturn('', 0, '订单号错误', 0);
            }
        }
    }

    public function saveSupplier()
    {
        $get_order = $this->db->useGlobalScope(false)->where('order_no', $this->post ['order_no'])->find()->toArray();
        $temp_log = array();
        $temp_log ['supplier_id'] = $this->post ['supplier_id'];
        $memberdb = new Memberdb ();
        $get_supplier = $memberdb->useGlobalScope(false)->where('member_id', $this->post ['supplier_id'])->find()->toArray();
        $temp_log ['supplier_name'] = $get_supplier ['supplier_name'];
        $temp_log ['zhipai_date'] = date('Y-m-d H:i:s', time());
        $supplier_log_arr = array();
        $data = array();
        if ($get_order ['reset_suppler']) {
            $supplier_log_arr = json_decode($get_order ['reset_suppler'], true);
            $data ['is_reset'] = 1;
        }
        array_push($supplier_log_arr, $temp_log);
        $data ['supplier_id'] = $this->post ['supplier_id'];
        $data ['supplier_rate'] = $this->post ['supplier_rate'];
        $data ['supplier_state'] = 3;
        $data ['push_supplier_time'] = time();
        $data ['xsht'] = '';
        $data ['cght'] = '';
        $data ['shd'] = '';
        $data ['xsfp'] = '';
        $data ['cgfp'] = '';
        $data ['reset_suppler'] = json_encode($supplier_log_arr);
        if (in_array($data['supplier_id'], [594, 601])) {
            $data['supplier_er'] = $data['supplier_id'];
        }

        // 处理泰隆吉消息队列
        if ($get_order['supplier_id']) {
            pushTljMsg('transfer_order', array('order_no' => $get_order['out_order_no']), $get_order['supplier_id']);
        }
        pushTljMsg('assign_order', array('order_no' => $get_order['out_order_no']), $this->post['supplier_id']);
        // 处理队列结束
        $this->db->save($data, [
            'order_no' => $this->post ['order_no']
        ]);
        // 验证是否需要同步到分系统
        $UOrderdb = new UOrderdb();
        $UOrderdb->param['supplier_id'] = $this->post['supplier_id'];
        $UOrderdb->param['order_no'] = $this->post['order_no'];
        $UOrderdb->saveOrder();

        // 同步分系统结束
        $get_order = Db::table('__ORDER__ o')->where('o.order_no', $this->post ['order_no'])->join('__MEMBER__ m', 'm.member_id = o.supplier_id')->field('o.order_money,m.phone,o.api_param,o.out_order_no,m.supplier_name')->find();
        if ($get_order) {
            $get_param = json_decode($get_order ['api_param'], true);
            $msg_json ['order'] = $get_order ['out_order_no'];
            $msg_json ['money'] = $get_order ['order_money'] / 100;
            $msg_json ['address'] = $get_param ['Cityname'] . $get_param ['address'];

            /*if ($get_order['phone']) {
                $phone = $get_order['phone'];
            } else {
                $phone = $get_param['mobile'];
            }*/

            $phone = $get_supplier['phone'];
            if ($phone) {
                $this->sendMsg($phone, 'SMS_225925355', $msg_json);
            }
            //sendEmail($get_order ['phone'], '新增订单', '订单号：' . $msg_json['order'] . '，订单金额：' . $msg_json['money'] . '，地址：' . $msg_json['address']);
        }


        Cache::clear('order');
        if (isset ($this->post ['offer_id']) && $this->post ['offer_id']) {
            $offerdb = new Offerdb ();
            $offerdb->param ['offer_id'] = $this->post ['offer_id'];
            $offerdb->param ['is_used'] = 1;
            $offerdb->ajaxSave();
        }
        // 流转日志
        $order_logdb = new OrderLogdb ();
        $order_logdb->param = array(
            'type_index' => 2,
            'order_no' => $this->post ['order_no'],
            'member_id' => MEMBER_ID,
            'view_text' => '指派供应商【' . $get_order ['supplier_name'] . '】',
            'post_json' => $this->post
        );
         $order_logdb->saveData();
        $this->layuiReturn('保存成功');
    }

    public function saveData()
    {
        $return = $this->db->addOrder();
        if ($return != 'success') {
            $this->layuiReturn($return, 0, $return, -1);
        } else {
            $this->layuiReturn('保存成功');
        }
    }

    public function editOrder()
    {
        $return = $this->db->editOrder();
        if ($return == 'success') {
            $this->layuiReturn('保存成功');
        } else {
            $this->layuiReturn($return, 0, $return, -1);
        }
    }

    /**
     * Title("修改订单备注3信息")
     */
    public function cartBeizhu()
    {
        $cartdb = new Cartdb();
        $get_cart = $cartdb->where('order_no', $this->post['order_no'])->where('goods_sku', $this->post['goods_sku'])->find();
        if ($get_cart) {
            $get_cart->save(['goods_beizhu3' => $this->post['value']]);
            // 写日志
            $remark_log = [];
            $remark_log['order_no'] = $this->post['order_no'];
            $remark_log['goods_sku'] = $this->post['goods_sku'];
            $remark_log['goods_name'] = Db::name('goods')->where('goods_sku', $this->post['goods_sku'])->value('goods_name');
            $remark_log['member_id'] = MEMBER_ID;
            $remark_log['username'] = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
            $remark_log['value'] = $this->post['value'];
            $remark_log['date'] = date('Y-m-d H:i:s');
            $remarkLogdb = new OrderGoodsRemarkdb();
            $remarkLogdb->save($remark_log);
            // 日志结束
            // 同步分系统
            $ucartdb = new UCartdb();
            $get_u_cart = $ucartdb->where('order_no', $this->post['order_no'])->where('goods_sku', $this->post['goods_sku'])->find();
            if ($get_u_cart) {
                $get_u_cart->save(['goods_beizhu3' => $this->post['value']]);
                // 同步日志
                $jremarkLogdb = new UOrderGoodsRemarkdb();
                $jremarkLogdb->save($remark_log);
            }
        }
        $this->layuiReturn('保存成功');
    }

    /**
     * Title("获取订单商品备注修改日志")
     */
    public function orderGoodsRemarkLog()
    {
        $data = Db::name('order_goods_remark')->where('order_no', $this->post['order_no'])->order('id desc')->select();
        $this->layuiReturn($data);
    }

    /**
     * 修改供应商折扣率
     */
    public function resetSupplierRate()
    {
        $get_order = $this->db->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            $get_order->save(['supplier_rate' => $this->post['supplier_rate']]);
            $this->layuiReturn('保存成功');
        } else {
            $this->layuiReturn('错误', 0, '', -1);
        }
    }

    public function addExpress()
    {
        $return = $this->db->addExpress();
        if ($return == 'success') {
            $this->layuiReturn('保存成功');
        } else {
            $this->layuiReturn($return, 1, $return, 1);
        }
    }

    public function tplForm()
    {
        $this->assign('member_cols', json_encode($this->member_cols));
        $this->assign('goods_cols', json_encode($this->goods_cols));
        $this->assign('select_goods_cols', json_encode($this->select_goods_cols));
        return $this->fetch();
    }

    public function addInstallInfo()
    {
        $installdb = new Installdb ();
        $installdb->param = $this->post;
        $installdb->addInstallInfo();
        $this->layuiReturn('保存成功');
    }

    // 支付信息
    public function addPayInfo()
    {
        $this->db->param = array();
        $this->db->param ['event'] = 'add_pay';
        $this->db->param ['order_no'] = $this->post ['order_no'];
        $cartdb = new Cartdb ();
        $cartdb->param ['order_no'] = $this->post ['order_no'];
        $this->db->param ['cart_ids'] = $cartdb->ajaxCartIds();
        unset ($this->post ['order_no']);
        $this->post ['pay_state'] = $this->post ['pay_state'];
        $this->post ['pay_time'] = time();
        $this->db->param ['post_data'] = $this->post;
        $this->db->editOrder();
        $this->layuiReturn('支付成功');
    }

    public function returned()
    {
        $returneddb = new Returneddb ();
        $returneddb->param = $this->post;
        $returneddb->ajaxSave();
        // 处理cart
        $cartdb = new Cartdb ();
        $cartdb->param ['order_no'] = $this->post ['order_no'];
        $cartdb->param ['goods_sku'] = $this->post ['goods_sku'];
        if ($this->post ['returned_type'] == 1) {
            // 退货
            $cartdb->param ['returned_state'] = 2;
        } else {
            $cartdb->param ['returned_state'] = 4;
        }
        $cartdb->setReturned();
        $this->layuiReturn('保存成功');
    }

    public function optionLog($order_no)
    {
        // 调用日志
        $orderLogdb = new OrderLogdb ();
        $orderLogdb->param ['order_no'] = $order_no;
        $get_log = $orderLogdb->ajaxList();
        $this->assign('order_log', $get_log);
        return $this->fetch();
    }

    /**
     *
     * @todo 软删除
     */
    public function ajaxDelete()
    {
        $this->db->param = $this->post;
        $this->db->ajaxDelete();
        $this->layuiReturn('删除成功', 0);
    }

    /**
     * Title("重新生成采购发票和销售发票")
     */
    public function resetCght()
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            $get_order->save(['cght' => '生成中']);
            $save_data = [];
            $temp1 = [];
            $temp1['order_no'] = $get_order['order_no'];
            $temp1['buildtpl_type'] = 'cght';
            $temp1['state'] = 2;
            array_push($save_data, $temp1);
            $buildtpldb = new Buildtpldb();
            $buildtpldb->saveAll($save_data);
        }
        $this->layuiReturn('success');
    }

    // 重新生成采购发票和销售发票
    public function resetfp()
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            $get_order->save(['xsfp' => '生成中', 'cgfp' => '生成中']);
            //$orderdb->where('order_id', $get_order['order_id'])->update([$this->post['type'] => '生成中']);
            $save_data = [];
            $temp1 = [];
            $temp1['order_no'] = $get_order['order_no'];
            $temp1['buildtpl_type'] = 'xsfp';
            $temp1['state'] = 2;
            array_push($save_data, $temp1);
            $temp2 = [];
            $temp2['order_no'] = $get_order['order_no'];
            $temp2['buildtpl_type'] = 'cgfp';
            $temp2['state'] = 2;
            array_push($save_data, $temp2);
            $buildtpldb = new Buildtpldb();
            $buildtpldb->saveAll($save_data);
        }
        $this->layuiReturn('success');
    }

    /**
     * @回滚订单
     */
    public function backOrder()
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $this->post['order_no'])->find();
        if (!$get_order) {
            $this->layuiReturn('订单号错误');
        }
        $log_txt = '';
        switch ($this->post['back_state']) {
            case '1':
                $get_order->save(['supplier_id' => 0, 'supplier_rate' => 0, 'supplier_state' => 2, 'push_supplier_time' => null, 'supplier_confirm_time' => null]);
                $log_txt = '指派订单';
                break;
            case '2':
                $get_order->save(['gys_fh_time' => null, 'gys_fh_state' => 2, 'wuliu' => null, 'wuliudanhao' => null]);
                $log_txt = '供应商发货';
                break;
            case '3':
                $get_order->save(['gys_sh_state' => 2, 'gys_sh_time' => null]);
                $log_txt = '供应商收货';
                break;
            case '4':
                $get_order->save(['shopping_state' => 1, 'shopping_time' => null, 'order_state' => 2]);
                $cartdb = new Cartdb();
                $get_cart = $cartdb->where('order_no', $this->post['order_no'])->select();
                if (!empty($get_cart)) {
                    foreach ($get_cart as $key => $val) {
                        $val->save(['pack_state' => 2, 'pack_id' => null]);
                    }
                }
                $log_txt = '发货军采';
                break;
            case '5':
                $get_order->save(['receipt_state' => 1, 'receipt_time' => null, 'order_state' => 3]);
                $cartdb = new Cartdb();
                $get_cart = $cartdb->where('order_no', $this->post['order_no'])->select();
                if (!empty($get_cart)) {
                    foreach ($get_cart as $key => $val) {
                        $val->save(['receipt_state' => 2, 'receipt_time' => null]);
                    }
                }
                $expressdb = new Expressdb();
                $get_express = $expressdb->where('order_no', $this->post['order_no'])->select();
                if (!empty($get_express)) {
                    foreach ($get_express as $key => $val) {
                        $val->save(['receipt_state' => 1, 'receipt_time' => null]);
                    }
                }
                $log_txt = '收货军采';
                break;
            case '6':
                $get_order->save(['invoice_time' => null, 'invoice_state' => 1]);
                $invoicedb = new Invoicedb();
                $get_invoice = $invoicedb->where('order_nos', $this->post['order_no'])->select();
                if (!empty($get_invoice)) {
                    foreach ($get_invoice as $key => $val) {
                        $val->save(['state' => 1, 'invoice_time' => null, 'invoice_proof' => null]);
                    }
                }
                $log_txt = '上传发票';
                break;
            case '7':
                $get_order->save(['caigou_invoice_duty' => null, 'caigou_invoice_pz' => null, 'caigou_state' => 1]);
                $invoicedb = new Invoicedb();
                $get_invoice = $invoicedb->where('order_nos', $this->post['order_no'])->select();
                if (!empty($get_invoice)) {
                    foreach ($get_invoice as $key => $val) {
                        $val->save(['gys_state' => 1]);
                    }
                }
                $log_txt = '供应商发票';
                break;
            case '8':
                $get_order->save(['returncode' => null, 'is_down' => 2, 'invoice_state' => 1]);
                $invoicedb = new Invoicedb();
                $get_invoice = $invoicedb->where('order_nos', $this->post['order_no'])->select();
                if (!empty($get_invoice)) {
                    foreach ($get_invoice as $key => $val) {
                        $val->save(['state' => 1, 'api_bianhao' => null, 'invoice_time' => null, 'invoice_proof' => null, 'api_return_no' => null, 'fapiaohao' => null, 'fapiaodaima' => null, 'api_type' => null, 'api_date' => null]);
                    }
                }
                $log_txt = '电子发票';
                break;
            default:
                break;
        }
        // 写订单日志
        $save_log = [];
        $save_log['order_no'] = $this->post['order_no'];
        $save_log['member_id'] = MEMBER_ID;
        $save_log['view_text'] = '订单初始化状态：' . $log_txt;
        $save_log['post_json'] = "";
        $save_log['type_index'] = 102;
        $orderlogDb = new OrderLogdb();
        $orderlogDb->save($save_log);
        // 同步分系统日志
        $uorderlogDb = new UOrderLogdb();
        $uorderlogDb->save($save_log);
        $this->layuiReturn('回滚成功');
    }

    // 手动生成验收单
    public function exportyanshoudan()
    {
        $data ['ysd'] = '生成中';
        $this->db->save($data, [
            'order_no' => $this->post ['order_no']
        ]);
        $this->db->clearCache();
        $tpl ['buildtpl_type'] = 'ysd';
        $tpl ['order_no'] = $this->post ['order_no'];
        $buildtpldb = new Buildtpldb();
        $buildtpldb->save($tpl);
        $this->layuiReturn('保存成功');
    }

    /*
     * 手动生成验收单
     */
    public function exportYanshoudan_back($order_no)
    {
        ini_set('max_execution_time', 0);
        // $order_ids = $this->post['order_ids'];
        $html = '';
        $pdf = new \TCPDF ('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
        $pdf->SetFont('stsongstdlight', 'B', 12);
        $pdf->setFontSubsetting(false);
        $file_url = 'https://' . $_SERVER ['HTTP_HOST'] . url('supplier/buildtpl/yanshoudan', array(
                'order_no' => $order_no
            ));
        $html = file_get_contents($file_url);
        $pdf->AddPage();
        $pdf->writeHTML($html);
        $all_page = $pdf->getNumPages();
        $orderdb = new Orderdb ();
        $get_order = $orderdb->where('order_no', $order_no)->find();
        if ($get_order) {
            $get_order = $get_order->toArray();
            $pdf->Output($_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/ysd/' . $get_order ['out_order_no'] . '验收单.pdf', 'F');
            $hetong = new Hetong ();
            $hetong->uploadOpt($get_order ['out_order_no'], 'ysd', $all_page);
            $uorderdb = new UOrderdb();
            $get_uorder = $uorderdb->where('order_no', $order_no)->find();
            if ($get_uorder) {
                $get_uorder->save(['ysd' => 'https://' . $_SERVER ['HTTP_HOST'] . '/uploads/Excel/hetong/' . $get_uorder['out_order_no'] . '验收单.pdf']);
            }
            $this->layuiReturn('验收单生成成功', 0, '', 1);
        } else {
            return 'error';
        }
    }

    /**
     * Title("发送邮件附件")
     */
    public function sendMailAttr()
    {
        $order_db = new Orderdb();
        $get_order = $order_db->where('order_no', $this->post['order_no'])->find();
        if ($get_order) {
            // 添加zip
            $zip_name = 'uploads/Excel/zip/' . $get_order['out_order_no'] . '打包信息' . date('Ymdhi') . '.' . rand(1000, 9999) . '.zip';
            $attr_name = $get_order['out_order_no'] . '打包信息.zip';
            $zip = new \ZipArchive();
            $zip->open($zip_name, \ZipArchive::CREATE);
            if ($zip == true) {
                $base_url = '/www/wwwroot/dxtadmin/';
                // 添加销售合同
                $xs_file = 'uploads/Excel/sale/' . $get_order['out_order_no'] . '销售合同.pdf';
                if (file_exists($base_url . $xs_file)) {
                    $zip->addFile($base_url . $xs_file, '销售合同.pdf');
                }
                // 添加送货单
                $shd_file = 'uploads/Excel/hetong/' . $get_order['out_order_no'] . '送货验收单.pdf';
                if (file_exists($base_url . $shd_file)) {
                    $zip->addFile($base_url . $shd_file, '送货单.pdf');
                }
                // 添加验收单
                $ysd_file = 'uploads/Excel/hetong/' . $get_order['out_order_no'] . '验收单.pdf';
                if (file_exists($base_url . $ysd_file)) {
                    $zip->addFile($base_url . $ysd_file, '验收单.pdf');
                }
                // 添加发票
                $get_invoice = Db::name('upload')->where('upload_id', Db::name('invoice')->where('order_nos', $get_order['order_no'])->value('invoice_proof'))->find();
                if ($get_invoice) {
                    $fp_file = str_replace('./', 'uploads/', $get_invoice['save_path']);
                    $fp_file = str_replace('https://tailongji.dixintong.com/', '', $fp_file);
                    $fp_file = str_replace('http://tailongji.dixintong.com/', '', $fp_file);
                    $fp_file = str_replace('https://fen.utecbj.com/', '', $fp_file);
                    $fp_file = str_replace('http://fen.utecbj.com/', '', $fp_file);
                    if (file_exists($base_url . $fp_file)) {
                        $zip->addFile($base_url . $fp_file, '发票.pdf');
                    }
                }
                // 添加采购发票
                if (stripos($get_order['cgfp'], 'http') === 0) {
                    $fp_file = str_replace('./', 'uploads/', $get_order['cgfp']);
                    $fp_file = str_replace('https://tailongji.dixintong.com/', '', $fp_file);
                    $fp_file = str_replace('http://tailongji.dixintong.com/', '', $fp_file);
                    $fp_file = str_replace('https://fen.utecbj.com/', '', $fp_file);
                    $fp_file = str_replace('http://fen.utecbj.com/', '', $fp_file);
                    if (file_exists($base_url . $fp_file)) {
                        $zip->addFile($base_url . $fp_file, '采购发票.xls');
                    }
                }
            }
            $zip->close();
            $result = $this->sendMailTpl($this->post['to_mail'], $_SERVER['DOCUMENT_ROOT'] . '/' . $zip_name, $get_order['out_order_no'] . '--泰龙吉', $attr_name);
            if ($result == true) {
                // 修改订单状态
                $params = json_decode($get_order['api_param'], true);
                $save_order = [];
                $save_order['is_send_mail'] = 1;
                if ($params['email'] != $this->post['to_mail']) {
                    $params ['email'] = $this->post['to_mail'];
                    $save_order['api_param'] = json_encode($params);
                }
                $get_order->save($save_order);
                // 同步分系统
                $jorderdb = new UOrderdb();
                $get_j_order = $jorderdb->where('order_no', $get_order['order_no'])->find();
                if ($get_j_order) {
                    $get_j_order->save($save_order);
                }
                $this->layuiReturn('', 1, '发送成功', 1);
            } else {
                $this->layuiReturn('', 1, '邮件发送失败', 2);
            }
        } else {
            $this->layuiReturn('', 1, '订单失败', 2);
        }

    }

    /**
     * Title("打包采购发票")
     */
    public function daobaocaigoufapiao($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace('http', '', str_replace('https', '', $file));
        $file = str_replace('://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allRow = $sheet->getHighestRow();
        $order_arr = [];
        $order_price = [];
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $out_order_no = $sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                array_push($order_arr, $out_order_no);
            }
        }
        if (count($order_arr) > 0) {
            $orderdb = new Orderdb();
            $get_order = $orderdb->whereIn('out_order_no', $order_arr)->field('cgfp,out_order_no')->select();
            if (!$get_order->isEmpty()) {
                $zip_name = 'uploads/hetong/采购发票' . time() . '.zip';
                $zip = new \ZipArchive ();
                $res = $zip->open($zip_name, \ZipArchive::CREATE);
                if (!$res) {
                    halt('创建打包文件错误');
                }
                $excel_data = [];
                foreach ($get_order as $key => $val) {
                    if ($val ['cgfp']) {
                        $ht_src = str_replace('https://tailongji.dixintong.com/', '', str_replace($this->base_url, '', $val ['cgfp']));
                        $ht_src = str_replace('http://tailongji.dixintong.com/', '', $ht_src);
                        $zip->addFile($ht_src, $val['out_order_no'] . '采购发票.xls');
                    } else {
                        array_push($excel_data, array('out_order_no' => $val['out_order_no']));
                    }
                }

                // 如果有不匹配的数据 添加excel文档
                if (count($excel_data)) {
                    $excel_name = '未匹配信息.xls';
                    $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
                    $obj_act_sheet = $phpExcel->getActiveSheet();
                    $header_data = array(
                        '订单号'
                    );
                    $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
                    $down_data = [];
                    foreach ($excel_data as $key => $val) {
                        // 处理文件夹名称
                        $temp = [];
                        $temp[0] = $val['out_order_no'];
                        $temp[1] = '';
                        array_push($down_data, $temp);
                    }
                    $vAlign = new \PHPExcel_Style_Alignment ();
                    $this->setExcelBodyInvoice($obj_act_sheet, $phpExcel, $down_data, count($header_data), $vAlign::VERTICAL_CENTER);
                    $obj_write->save('./uploads/Excel/zip/' . $excel_name);
                    $zip->addFile('./uploads/Excel/zip/' . $excel_name, $excel_name);
                }

                $zip->close();
                $this->layuiReturn('success', 'https://tailongji.dixintong.com/' . $zip_name);
            } else {
                $this->layuiReturn('error', '没有可导出信息2', -1);
            }
        } else {
            $this->layuiReturn('error', '没有可导出信息', -1);
        }
    }

    /**
     * Title("合并采购发票")
     */
    public function mergeInvoice($file)
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace('http', '', str_replace('https', '', $file));
        $file = str_replace('://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allRow = $sheet->getHighestRow();
        $order_arr = [];
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $out_order_no = $sheet->getCellByColumnAndRow(0, $rowIndex)->getValue();
                array_push($order_arr, $out_order_no);
            }
        }
        if (count($order_arr) > 0) {
            $excel_name = '合并采购发票_' . date('Y-m-d H:i:s') . '.xls';
            $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
            $obj_act_sheet = $phpExcel->getActiveSheet();
            $header_data = array(
                '订单号',
                '单位名称',
                '纳税识别号',
                '地址、电话',
                '开户行及账号',
                '税务大类',
                '税务编码',
                '商品名称',
                '开票名称',
                '规格型号',
                '数量',
                '单位',
                '采购单价（元）',
                '采购金额（元）'
            );
            $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
            $order_sql = Db::name('order')->fetchSql(true)->whereIn('out_order_no', $order_arr)->column('order_no');
            $get_cart = Db::table('__CART__ c')
                //->fetchSql(true)
                ->whereExp('c.order_no', 'in(' . $order_sql . ')')
                ->field('
                    o.out_order_no,
                    g.product_area,
                    c.product_area product_areas,
                    g.shuiwu_id,
                    c.shuiwu_id shuiwu_ids,
                    g.goods_name,
                    g.product_firm,
                    c.product_firm product_firms,
                    g.invoice_model,
                    c.invoice_model invoice_models,
                    c.goods_num,
                    g.goods_unit,
                    c.goods_unit goods_units,
                    c.goods_price,
                    o.supplier_rate
                    ')
                ->join('__GOODS__ g', 'g.goods_sku = c.goods_sku')
                ->join('__ORDER__ o', 'o.order_no = c.order_no')
                ->select();
            $excel_data = array();
            if (!$get_cart->isEmpty()) {
                foreach ($get_cart as $k => $v) {
                    unset ($temp);
                    $temp [0] = "\t" . $v ['out_order_no'];
                    $temp [1] = '北京市泰龙吉贸易有限公司';
                    $temp [2] = '91110105675715354X';
                    $temp [3] = '北京市朝阳区管庄乡杨闸村京通辅路南8号院 F1 010-59521909';
                    $temp [4] = '交通银行北京林萃路支行  110061203018010014524';
                    $temp [5] = $v ['product_areas'] ?: $v['product_area'];
                    $temp [6] = "\t" . ($v ['shuiwu_ids'] ?: $v['shuiwu_id']);
                    $temp [7] = $v ['goods_name'];
                    $temp [8] = $v ['product_firms'] ?: $v['product_firm'];
                    $temp [9] = $v ['invoice_models'] ?: $v['invoice_model'];
                    $temp [10] = $v ['goods_num'];
                    $temp [11] = $v['goods_units'] ?: $v['goods_unit'];
                    if ($v ['supplier_rate'] > 0) {
                        $cg_price = round($v ['goods_price'] * $v ['supplier_rate']) / 100;
                    } else {
                        $cg_price = $v ['goods_price'];
                    }
                    $temp [12] = ' ' . number_format($cg_price, 2, '.', '');
                    $temp [13] = ' ' . number_format($temp [10] * $cg_price, 2, '.', '');
                    array_push($excel_data, $temp);
                }
                $vAlign = new \PHPExcel_Style_Alignment ();
                $this->setExcelBody6($obj_act_sheet, $phpExcel, $excel_data, count($header_data), $vAlign::VERTICAL_CENTER);
                $obj_write->save('./uploads/Excel/invoicecallet/' . $excel_name);
                $this->layuiReturn('success', 'https://tailongji.dixintong.com/uploads/Excel/invoicecallet/' . $excel_name);
            } else {
                $this->layuiReturn('error', '没有可导出信息', -1);
            }
        }
    }

    /**
     * Title("获取快递公司列表")
     */
    public function KuaidiList()
    {
        $get_com = Db::name('kuaidi')->order('kuaidi_id asc')->column('kuaidiname');
        $this->layuiReturn($get_com, count($get_com), 'success', 1);
    }

    /**
     * Title("获取订单独立商品")
     */
    public function outGoods()
    {
        $data = Db::name('order_out_goods')->where('order_no', $this->post['order_no'])->order('id desc')->select();
        $this->layuiReturn($data);
    }

    /**
     * Title("保存独立商品")
     */
    public function saveOutGoods()
    {
        $save_data = $this->post;
        unset($save_data['out_goods_id']);
        unset($save_data['out_goods_order_no']);
        $save_data['order_no'] = $this->post['out_goods_order_no'];
        $outGoodsdb = new OrderOutGoodsdb();
        if ($this->post['out_goods_id']) {
            $get_out_goods = $outGoodsdb->find($this->post['out_goods_id']);
            $get_out_goods->save($save_data);
        } else {
            $outGoodsdb->save($save_data);
        }
        $this->layuiReturn('success');
    }

    /**
     * Title("删除独立商品")
     */
    public function deleteOutGoods()
    {
        $outGoodsdb = new OrderOutGoodsdb();
        $outGoodsdb->where('id', $this->post['id'])->delete();
        $this->layuiReturn('success');
    }

    /**
     * Title("验证订单是否新手机号和新地址")
     */
    public function comNewCustom()
    {
        $pikuanxinxidb = new Pikuanxinxidb();
        $chk_phone = $pikuanxinxidb->where('phone', $this->post['phone'])->count();
        $chk_addr = $pikuanxinxidb->where('address', $this->post['addr'])->count();
        $result = [];
        $result['phone_flag'] = $chk_phone > 0 ? '否' : '是';
        $result['addr_flag'] = $chk_addr > 0 ? '否' : '是';
        $this->layuiReturn($result);
    }

    /**
     * Title("导入excel生成合同")
     */
    public function createContract()
    {
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $files = request()->file();
        vendor("PHPExcel.PHPExcel");
        $phpExcel = new \PHPExcel ();
        // 上传文件
        $order_arr = [];
        foreach ($files as $file) {
            $info = $file->validate([
                'site' => 1024 * 10 * 1024 * 1024,
                'ext' => 'xls,xlsx'
            ])->move('./uploads/');
            if ($info) {
                $fileName = './uploads/' . $info->getSaveName();
                $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                $objReader->setReadDataOnly(true);
                $objPHPExcel = $objReader->load($fileName, $encode = 'utf-8');
                $sheet = $objPHPExcel->getSheet();
                $get_row_num = $sheet->getHighestRow(); // 总行数
                $the_sheet = $objPHPExcel->getActiveSheet();
                $save_build = [];
                for ($i = 2; $i <= $get_row_num; $i++) {
                    $out_order_no = (string)$this->getSheetValue($the_sheet, "A" . $i);
                    $order_no = Db::name('order')->where('out_order_no', $out_order_no)->value('order_no');
                    if ($order_no) {
                        $type = $this->getSheetValue($the_sheet, "B" . $i);
                        $buildtpl_type = '';
                        switch ($type) {
                            case '1':
                                $buildtpl_type = 'xsht';
                                break;
                            case '2':
                                $buildtpl_type = 'cght';
                                break;
                            case '3':
                                $buildtpl_type = 'shd';
                                break;
                            case '4':
                                $buildtpl_type = 'ysd';
                                break;
                            case '5':
                                $buildtpl_type = 'xsfp';
                                break;
                            case '6':
                                $buildtpl_type = 'cgfp';
                                break;
                        }
                        $temp = [];
                        $temp['order_no'] = $order_no;
                        $temp['buildtpl_type'] = $buildtpl_type;
                        $temp['state'] = 2;
                        $temp['create_time'] = time();
                        array_push($save_build, $temp);
                    }
                }
                if (count($save_build)) {
                    $buildtpldb = new Buildtpldb();
                    $buildtpldb->saveAll($save_build);
                    $this->layuiReturn('提交成功,正在生成', 0, '提交成功,正在生成', 1);
                } else {
                    $this->layuiReturn('导入订单错误', 0, '导入订单错误', 2);
                }

            } else {
                $this->layuiReturn($file->getError(), 0, $file->getError(), 2);
            }
        }
    }

    /**
     * Title("导入订单号导出对应的文件对象")
     */
    public function downCght($file, $type)
    {
        $cn_name = '';
        switch ($type) {
            case 'cght':
                $cn_name = '采购合同';
                break;
            case 'xsfp': // 调用发票表中的数据
                $cn_name = '销售发票';
                break;
            case 'cgfp':
                $cn_name = '采购发票';
                break;
        }
        set_time_limit(3600);
        ini_set('memory_limit', '256M');
        $file = str_replace($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'], '.', $file);
        vendor("PHPExcel.PHPExcel");
        Vendor('PHPExcel.Classes.PHPExcel.Worksheet.Drawing');
        Vendor('PHPExcel.Classes.PHPExcel.Writer.Excel2007');
        $phpExcel = new \PHPExcel ();
        $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if ($extension == 'xlsx') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        } else if ($extension == 'xls') {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }
        $objPHPExcel = $objReader->load($file);
        $sheet = $objPHPExcel->getSheet(0);
        $allRow = $sheet->getHighestRow();
        $order_no_arr = [];
        for ($rowIndex = 2; $rowIndex <= $allRow; $rowIndex++) { // 循环读取每个单元格的内容。注意行从1开始，列从A开始
            if ($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue()) {
                $order_no = trim($sheet->getCellByColumnAndRow(0, $rowIndex)->getValue());
                array_push($order_no_arr, $order_no);
            }
        }

        if($type == 'xsfp'){
            $order_cght = Db::name('order')->alias('o')
                ->join('invoice i','o.order_no=i.order_nos','LEFT')
                ->join('upload u','u.upload_id = i.invoice_proof','LEFT')
                ->whereIn('o.out_order_no', $order_no_arr)
                ->field('o.out_order_no,u.save_path xsfp')
                ->select();
        } else {
            $order_cght = Db::name('order')->whereIn('out_order_no', $order_no_arr)->field($type . ',out_order_no')->select();
        }
        if ($order_cght->isEmpty()) {
            $this->layuiReturn('', 0, '没有可导出信息', -1);
        }
        $zip_name = 'uploads/hetong/'.$cn_name . time() . '.zip';
        $zip = new \ZipArchive ();
        $res = $zip->open($zip_name, \ZipArchive::CREATE);
        if (!$res) {
            halt('创建打包文件错误');
        }
        $excel_data = [];
        foreach ($order_cght as $key => $val) {
            if ($val [$type]) {
                if($type == 'xsfp'){
                    $ext = explode('.', $val [$type]);
                    if (!$zip->addFile('./uploads/' . $val [$type], $val['out_order_no'] . $cn_name . '.' . end($ext))) {
                        array_push($excel_data, array('out_order_no' => $val['out_order_no']));
                    }
                } else {
                    $temp = explode('uploads', $val[$type]);
                    if (count($temp) == 2) {
                        $ext = explode('.', $temp[1]);
                        if (!$zip->addFile('./uploads/' . $temp[1], $val['out_order_no'] . $cn_name . '.' . end($ext))) {
                            array_push($excel_data, array('out_order_no' => $val['out_order_no']));
                        }
                    } else {
                        array_push($excel_data, array('out_order_no' => $val['out_order_no']));
                    }
                }

            } else {
                array_push($excel_data, array('out_order_no' => $val['out_order_no']));
            }
        }
        if (count($excel_data)) {
            $excel_name = '无'.$cn_name.'订单.xls';
            $obj_write = new \PHPExcel_Writer_Excel5 ($phpExcel);
            $obj_act_sheet = $phpExcel->getActiveSheet();
            $header_data = array(
                '订单号'
            );
            $this->setExcelHeader($obj_act_sheet, $phpExcel, $header_data);
            $down_data = [];
            foreach ($excel_data as $key => $val) {
                // 处理文件夹名称
                $temp = [];
                $temp[0] = $val['out_order_no'];
                $temp[1] = '';
                array_push($down_data, $temp);
            }
            $vAlign = new \PHPExcel_Style_Alignment ();
            $this->setExcelBodyCght($obj_act_sheet, $phpExcel, $down_data, count($header_data), $vAlign::VERTICAL_CENTER);
            $obj_write->save('./uploads/Excel/zip/' . $excel_name);
            $zip->addFile('./uploads/Excel/zip/' . $excel_name, $excel_name);
        }

        $zip->close();
        $this->layuiReturn($_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/' . $zip_name);
    }
    
    /**
     * Title("上传自定义图片")
     */
    public function upImgArr($order_no, $img)
    {

        $orderImagedb = new OrderImagedb();
        $get_last = $orderImagedb->where('order_no', $order_no)->where('up_admin_id', MEMBER_ID)->order('id desc')->find();
        if ($get_last) {
            if (time() - $get_last['upload_time'] > 300) {
                $room = date('YmdHi') . '_' . MEMBER_ID;
            } else {
                $room = $get_last['room'];
            }
        } else {
            $room = date('YmdHi') . '_' . MEMBER_ID;
        }
        $admin_name = Db::name('member')->where('member_id', MEMBER_ID)->value('username');
        $save_data = [];
        $save_data['order_no'] = $order_no;
        $save_data['room'] = $room;
        $save_data['up_admin_id'] = MEMBER_ID;
        $save_data['admin_name'] = $admin_name;
        $save_data['image_url'] = $img;
        $save_data['upload_time'] = time();
        $orderImagedb->save($save_data);

        $this->layuiReturn('success');
    }

    /**
     * Title("获取自定义上传图片")
     */
    public function getImage($order_no)
    {
        $orderImagedb = new OrderImagedb();
        $get_img = $orderImagedb->where('order_no', $order_no)->order('id desc')->select();
        $result = [];
        if (!$get_img->isEmpty()) {
            foreach ($get_img as $key => $val) {
                $result[$val['up_time']][] = $val->toArray();
            }
        }
        $this->assign('data', $result);
        return $this->fetch();
    }

    /**
     * Title("删除自定义图片")
     */
    public function delImage($id)
    {
        $orderImagedb = new OrderImagedb();
        $get_img = $orderImagedb->find($id);
        $get_img->delete();
        $this->layuiReturn('success');
    }

    /**
     * Title("获取自定义上传图片")
     */
    public function getImgArr($order_no)
    {
        $orderdb = new Orderdb();
        $get_img = $orderdb->where('order_no', $order_no)->value('img_arr');
        if ($get_img != '') {
            $this->layuiReturn(explode(',', $get_img));
        } else {
            $this->layuiReturn([]);
        }
    }
    
    /**
     * Title("获取自定义图片上传状态")
     */
    public function getImgState($order_no)
    {
        $orderImagedb = new OrderImagedb();
        $count = $orderImagedb->where('order_no', $order_no)->count();
        $this->layuiReturn('success', $count);
    }

    protected function setExcelBodyCght($obj_act_sheet, $phpExcel, $data, $count, $valign)
    {
        $start = 65;
        for ($i = 0; $i < $count; $i++) {
            if ($i >= 26) {
                $cell_value = chr(65) . chr($start + ($i - 26));
            } else {
                $cell_value = chr($start + $i);
            }
            $j = 2;
            $end_merge = 2;
            foreach ($data as $key => $val) {
                $obj_act_sheet->setCellValue($cell_value . $j, str_replace('_diff', '', str_replace('_add', '', $val [$i])));
                // 合并单元格
                $phpExcel->getActiveSheet()->getStyle($cell_value . $j)->getAlignment()->setVertical($valign);
                $j++;
            }
        }
        // 合并单元格
        $temp = '';
        $ceil_num = 0;
        $start_num = 2; // 第二行是正本数据
        for ($x = 0; $x < count($data); $x++) {
            if ($data [$x] [0] != $temp) {
                $temp = $data [$x] [0];
                if ($ceil_num > 1) {
                    for ($y = 0; $y < 0; $y++) {
                        $cell_value = chr($start + $y);
                        if ($y >= 26) {
                            $cell_value = 'A' . chr($start + $y - 26);
                        }
                        $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
                    }
                }
                $start_num += $ceil_num;
                $ceil_num = 1;
            } else {
                $ceil_num++;
            }
        }
        if ($ceil_num > 1) {
            for ($y = 0; $y < 0; $y++) {
                $cell_value = chr($start + $y);
                if ($y >= 26) {
                    $cell_value = 'A' . chr($start + $y - 26);
                }
                $phpExcel->getActiveSheet()->mergeCells($cell_value . $start_num . ':' . $cell_value . ($start_num + $ceil_num - 1));
            }
        }
    }
}